Reputation: 91
I'm just kind of confused with Python at the moment. I want to ask the user to input the date in a specific format. But I also want to check if there are two "/" in the input. Ex: MM/DD/YYYY.... or else I would output an error message.
This is what I have so far:
date = str((raw_input("Please enter a date in the form MM/DD/YYYY: ")))
while date[(2),(5)]!="/":
date_input=(str(raw_input("Error: Your date must be in the format YYYY/MM/DD including the slashes, try again: ")))
But I'm pretty stuck. Can anyone help me? Thanks.
Upvotes: 0
Views: 447
Reputation: 375584
Use datetime.strptime
to parse the date, and it will tell you when the format is wrong:
import datetime
d = datetime.datetime.now()
try:
d.strptime(date_str, "%d/%m/%Y")
except ValueError:
print "Bad format!"
Upvotes: 2