Gustav Westerlund Gustav Westerlund - 16 days ago 5
Python Question

Python Error Control Date

I want my program to take user input in form of a date and the control if it is valid. But with the code I have know the program say that it is wrong regardless of what format i give. I don't see the problem with the code:

import datetime
def visit_date():
while True:
date_visit = input("Enter the date you want to visit the Zoo in YYYY-MM-DD format: ")
try:
return datetime.datetime.strptime(date_visit, "%d/%m/%y")
except ValueError:
print("Not a valid format\n")

Answer

You're asking the user for a date in the format YYYY-MM-DD but then trying to parse it according to this format %d/%m/%y.

You instead should parse the string in the same way that you requested it, %Y-%m-%d