17

I would like to have the user input a date, something like:

date = input('Date (m/dd/yyyy): ')

and then make sure that the input is a valid date. I don't really care that much about the date format.

Thanks for any input.

3 Answers 3

26

You can use the time module's strptime() function:

import time
date = input('Date (mm/dd/yyyy): ')
try:
  valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
  print('Invalid date!')

Note that in Python 2.x you'll need to use raw_input instead of input.

Sign up to request clarification or add additional context in comments.

1 Comment

Or you can use the datetime module's strptime function. datetime.datetime.strptime( date, "%m/%d/%Y" ).
3
def validDate(y, m, d):
  Result = True
  try:
    d = datetime.date(int(y), int(m), int(d))
  except ValueError, e:
    Result = False
  return Result

and in the program use the function defined previously:

 if not validDate(year_file, month_file, day_file):
   return 0

Comments

2

Max S.,

Thanks for the code. Here is how I implemented it:

while True:
    date = input('Date (m/dd/yyyy): ')
        try:
            date = time.strptime(date, '%m/%d/%Y')
            break
        except ValueError:
            print('Invalid date!')
            continue

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.