Search code examples
pythondatetimedatetime-formatpython-datetime

How to validate a string input in python using datetime library and keep prompting user for input until valid input?


I have tried using this procedure:

import datetime
date_string = input()
format = "%Y-%m-%d"

try:
    datetime.datetime.strptime(date_string, format)
    print("This is the correct date string format.")
except ValueError:
    print("This is the incorrect date string format. It should be YYYY-MM-DD")

When I fill the input of the date_string with "2021-3-3" the output is

This is the correct date string format.

But when I do a little change to "2021-03-03" the output is

This is the incorrect date string format. It should be YYYY-MM-DD

How I make the second input to be true. So, when I input "2021-03-03" the output will also be

This is the correct date string format.

I also wanna know how to prompt the user until he input the right format, so that when he input the wrong format or value, the output is

This is the incorrect date string format, try again fill the

And, the program keep prompting user for input


Solution

  • This code works on my machine, and it prompts the user to input again if it doesn't succeed.

    import datetime
    format = "%Y-%m-%d"
    
    while(True):
        date_string = input("> ").strip()
        try:
            datetime.datetime.strptime(date_string, format)
            print("This is the correct date string format.")
            break
        except ValueError:
            print("This is the incorrect date string format. It should be YYYY-MM-DD")