Sep-03-2021, 11:11 AM
You can use datetime.datetime.strptime.
If you want that the user must enter Month Day Year, use as format_str "%m %d %y"
The format in my example:
%m = Month as a zero-padded decimal number.
%y = Year without century as a zero-padded decimal number.
%d = Day of the month as a zero-padded decimal number.
If you want that the user must enter Month Day Year, use as format_str "%m %d %y"
The format in my example:
"%m/%d/%y"
-> 12/31/21%m = Month as a zero-padded decimal number.
%y = Year without century as a zero-padded decimal number.
%d = Day of the month as a zero-padded decimal number.
import datetime def ask_date(): # https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes dt_format = "%m/%d/%y" # loop until the user inputs a valid date specified by # dt_format while True: user_input = input("Please enter the date (MM/DD/YY): ") try: # if strptime could not convert the str, then # a ValueError is raised as Exception date = datetime.datetime.strptime(user_input, dt_format).date() # datetime.datetime.strptime returns a datetime object and the method # date on the datetime object returns a date object derrived from datetime object # why? the date class has no Method for strptime because a date object could not store # a time, only dates. except ValueError: # input was invalid format # catching this Exception and printing an error print("Invalid date:", user_input) else: # the else block is only executed, if inside the # try-block no exception was thrown # return this new date object from this function # which leaves the while loop and leaves the function return date # calling the function and assign the returned object to a name user_date = ask_date() # this function repeats asking this question until the user has entered a valid date # here you can work with user_date, which is a date object. print(user_date)
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!