Search code examples
pythonpython-3.xvalidationinputvalueerror

How to raise customizable ValueError for input containing two dates?


I am trying to understand raising an exception little better.Below is python code, as you can see I am asking for two date inputs from user. If user types "2022" and hit enter it is returning python ValueError with msg "Not enough values to unpack (expected 2, got 1)". Instead what I would like to do is if user types year,month or date then instead of python default ValueError. It should raise an Error saying "Incorrect date entered, please enter dates in YYYY-MM-DD format ONLY" and should display the input box again for user to enter correct date. My question is how to raise customizable ValueError and ask the user to renter the dates?

Any help will be appreciated!

Code

def validate(date_text):
        try:
            for y in date_text:
                if not datetime.datetime.strptime(date_text, '%Y-%m-%d'):
                    raise ValueError
                else:
                    return True
        except ValueError:
            print("Incorrect date format, please enter dates in YYYY-MM-DD format ONLY")
            return False
while True:
    start_date,end_date= input("Enter employee start and termination date separated by (,)  in YYYY-MM-DD format only: ").split(",")
    if validate(start_date) and validate(end_date):
        break

Solution

  • I was able to resolve my issue using below code. Basically, I needed another try & except block in while statement. Thanks @Иван Балван for feedback!

    def validate(date_text):
            try:
                datetime.datetime.strptime(date_text, '%Y-%m-%d')
                return True
            except ValueError:
                print("Incorrect date format, please enter dates in YYYY-MM-DD format ONLY")
                return False
    
    while True:
        try:
            start_date,end_date= input("Enter employee start and termination date separated by (,)  in YYYY-MM-DD format only: ").split(",")
            if validate(start_date) and validate(end_date):
                break
        except ValueError:
            print("Incorrect date enetered, please enter both dates in YYYY-MM-DD format ONLY")