Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 266
Magwich Avatar asked Feb 07 '10 07:02

Magwich


People also ask

How do you validate a date?

The date validator requires day, month and year. If you are looking for hour and time validator, HH:mm , for example, you should use the regexp validator. Below are some example of possible formats: YYYY/DD/MM.

How do you check if the date is in YYYY MM DD format in Python?

There's no need to return the value, and there's no need to reinvent the wheel: just use datetime. datetime. strptime(date, "%Y-%m-%d") , which will either succeed or raise a ValueError .


1 Answers

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.

like image 164
Max Shawabkeh Avatar answered Oct 13 '22 21:10

Max Shawabkeh