0

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.

2
  • First you ask for a date in a certain format and put it in a certain variable, but then, if it has the wrong format, you then ask for it in a different format and put it in a different variable! By the way, raw_import returns a string, so there's no need to use str. Commented Jun 13, 2012 at 2:19
  • Also, date[(2),(5)] is invented syntax... Commented Jun 13, 2012 at 3:01

1 Answer 1

2

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!"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.