How can I validate a date in Python 3.x?
22,483
Solution 1
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
.
Solution 2
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
Solution 3
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
Author by
Magwich
I am a hobbyist programmer who likes to write useful code for others or myself. After trying out several languages over the last 20 years, I now mostly use Java and Python 3, and I am quite happy with them.
Updated on September 01, 2020Comments
-
Magwich over 3 years
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.
-
user1066101 about 14 yearsOr you can use the
datetime
module'sstrptime
function.datetime.datetime.strptime( date, "%m/%d/%Y" )
.