Magwich
Magwich

Reputation: 565

How can I validate a date in Python 3.x?

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.

Upvotes: 17

Views: 25229

Answers (3)

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

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.

Upvotes: 27

Karina
Karina

Reputation: 31

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

Upvotes: 3

Magwich
Magwich

Reputation: 565

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

Upvotes: 2

Related Questions