user1284619
user1284619

Reputation: 91

Python - checking for characters in date string

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

Answers (1)

Ned Batchelder
Ned Batchelder

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

Related Questions