开发者

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

开发者 https://www.devze.com 2022-12-19 22:36 出处:网络
I would like to have the user input a date, something开发者_如何转开发 like: date = input(\'Date (m/dd/yyyy): \')

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.


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消