John Allison
John Allison

Reputation: 367

What would be the simplest way to add exception handling to datetime input in my program's context?

I want to validate the input for the date as soon as it's called so that the user doesn't input all three and then receive an error/a prompt for the date again, but I can't figure out a way to do that. Do I need to restructure, or is there a way I'm missing?

I have a class object task defined as follows:

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()))

And the class is created through the function addTask which is defined as follows:

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()

Input is gathered as followed:

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

Upvotes: 1

Views: 26

Answers (1)

Kevin Welch
Kevin Welch

Reputation: 1508

One way to do this is to validate the datetime before it is passed to addTask in a try/except block.

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

There are more robust ways of doing validation, such as with the Marshmallow library, but that could be overkill for what you are working on.

Upvotes: 1

Related Questions