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.
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.
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 .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With