嗨我想在python中验证一些日期。但问题是我有一个特殊范围,例如,我的日期从1/1/2014
到08/07/2014
。所以我的问题是我如何验证格式和价值。我查看了此链接,但它只验证格式,但不验证具体值。
import time
date = input('Date (mm/dd/yyyy): ')enter date here
try:
valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
print('Invalid date!')
答案 0 :(得分:5)
使用time.strptime()
,然后验证生成的对象是否在您的范围内,而不是使用datetime.datetime.strptime()
:
from datetime import datetime, date
date_input = input('Date (mm/dd/yyyy): ')
try:
valid_date = datetime.strptime(date_input, '%m/%d/%Y').date()
if not (date(2014, 1, 1) <= valid_date <= date(2014, 8, 7)):
raise ValueError('Date out of range')
except ValueError:
print('Invalid date!')
如果没有抛出异常,valid_date
绑定到datetime.date()
instance。
答案 1 :(得分:2)
我想建议把它放到一个函数中:
from datetime import datetime
def validate_date(input_date, first=datetime(2014, 1, 1),
last=datetime(2014, 8, 7),
fmt='%m/%d/%Y'):
"""Return a validated datetime.datetime or None.
If the date has the wrong format return None, or if it is not in
the range [first,last] also return None. Otherwise return the
input_date as a datetime.datetime object.
"""
try:
d = datetime.strptime(input_date, fmt)
if not (first <= d <= last):
raise ValueError
except ValueError:
return None
else:
return d
# Example usage...
valid_date = validate_date(input('Date mm/dd/yyyy: '))
if valid_date is not None:
print(valid_date)
else:
print('Date not ok!')
答案 2 :(得分:0)
import datetime
inputDate = input("Enter the date in format 'dd/mm/yy' : ")
day,month,year = inputDate.split('/')
isValidDate = True
try :
datetime.datetime(int(year),int(month),int(day))
except ValueError :
isValidDate = False
if(isValidDate) :
print ("Input date is valid ..")
else :
print ("Input date is not valid..")