首页 > 解决方案 > 在我的程序上下文中向日期时间输入添加异常处理的最简单方法是什么?

问题描述

我想在调用日期后立即验证日期的输入,以便用户不会输入所有三个,然后再次收到错误/日期提示,但我想不出办法做到这一点。我需要重组,还是有什么方法我错过了?

我有一个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.")

标签: pythondatetime

解决方案


一种方法是在将日期时间传递给addTasktry/except 块之前对其进行验证。

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.")

有更强大的验证方法,例如使用 Marshmallow 库,但这对于您正在处理的工作来说可能是多余的。


推荐阅读