Reputation: 565
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
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
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
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