在程序上下文中将异常处理添加到datetime输入的最简单方法是什么?

2024-06-01 00:11:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在调用日期后立即验证输入,这样用户就不会输入所有三个,然后再次收到错误/日期提示,但我想不出一种方法。我需要重组吗,还是我缺少了一条路

我有一个类对象task定义如下:

class task:
    def __init__(self, name, due, category):
        self.name = name
        self.due = datetime.strptime(due, '%B %d %Y %I:%M%p')
        self.category = category
    def expand(self): # returns the contents of the task
        return str(self.name) + " is due in " + str((self.due - datetime.now()))

该类是通过函数addTask创建的,该函数定义如下:

def addTask(name, due, category):
    newTask = task(name, due, category)
    data.append(newTask)
    with open('./tasks.txt', 'wb') as file:
        pickle.dump(data, file)
    load_data()
    list_tasks()

收集的输入如下所示:

def ask():
    while True:
        arg = input("").lower()
        if arg == "add":
            addTask(input("What is the task? "),input("When's it due? "),input("What's the category? "))
        elif arg =="help":
            help()
        elif arg =="list":
            list_tasks()
        else:
            print("Command not recognized. Type 'help' for a list of commands.")

Tags: thenameselftaskinputdata定义def
1条回答
网友
1楼 · 发布于 2024-06-01 00:11:02

一种方法是在将日期时间传递给try/except块中的addTask之前验证日期时间

def ask():
    while True:
        arg = input("").lower()
        if arg == "add":
            task = input("What is the task? ")
            due = input("When's it due? ")
            category = input("What's the category? "))
            try:
                due = datetime.strptime(due, '%B %d %Y %I:%M%p')
            except ValueError:
                raise ValueError("Incorrect date format")
            addTask(task, due, category)
        elif arg =="help":
            help()
        elif arg =="list":
            list_tasks()
        else:
            print("Command not recognized. Type 'help' for a list of commands.")

有更可靠的方法进行验证,例如使用棉花糖库,但对于您正在进行的工作来说,这可能是过分的

相关问题 更多 >