Syn*_*nia 21 python validation time date
我正在构建一种日历网络应用程序
我在HTML中设置了以下表单
<form action='/event' method='post'>
Year ("yyyy"): <input type='text' name='year' />
Month ("mm"): <input type='text' name='month' />
Day ("dd"): <input type='text' name='day' />
Hour ("hh"): <input type='text' name='hour' />
Description: <input type='text' name='info' />
<input type='submit' name='submit' value='Submit'/>
</form>
Run Code Online (Sandbox Code Playgroud)
然后,来自用户的输入被提交到一个樱桃服务器中
我想知道,有没有办法检查用户输入的日期是否是有效日期?
显然我可以编写很多if语句,但有没有内置函数可以检查这个?
谢谢
Dhr*_*hak 24
您可以尝试使用datetime并处理异常以确定有效/无效日期:示例:http://codepad.org/XRSYeIJJ
import datetime
correctDate = None
try:
newDate = datetime.datetime(2008,11,42)
correctDate = True
except ValueError:
correctDate = False
print(str(correctDate))
Run Code Online (Sandbox Code Playgroud)
Rom*_*her 22
你可以试试
import datetime
datetime.datetime(year=year,month=month,day=day,hour=hour)
Run Code Online (Sandbox Code Playgroud)
这将消除一些事情,如月> 12,小时> 23,不存在的leapdays(月= 2非闰年最多28,否则29,其他月最多30或31天)(错误时抛出ValueError异常)
您也可以尝试将其与一些理智上/下限进行比较.例:
datetime.date(year=2000, month=1,day=1) < datetime.datetime(year=year,month=month,day=day,hour=hour) <= datetime.datetime.now()
Run Code Online (Sandbox Code Playgroud)
相关的上下理智取决于您的需求.
编辑:请记住,这不会处理某些日期时间可能对您的应用程序无效的事情(分钟生日,假期,外部营业时间等).
您可以尝试使用dateutil.parser模块来更轻松地解析日期:
from dateutil.parser import parse, ParserError
def is_valid_date(date):
if not date:
return False
try:
parse(date)
return True
except ParserError:
return False
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
使用datetime
例如。
>>> from datetime import datetime
>>> print datetime(2008,12,2)
2008-12-02 00:00:00
>>> print datetime(2008,13,2)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
print datetime(2008,13,2)
ValueError: month must be in 1..12
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用日期时间并处理异常来决定有效/无效日期:
import datetime
def check_date(year, month, day):
correctDate = None
try:
newDate = datetime.datetime(year, month, day)
correctDate = True
except ValueError:
correctDate = False
return correctDate
#handles obvious problems
print(str(check_date(2008,11,42)))
#handles leap days
print(str(check_date(2016,2,29)))
print(str(check_date(2017,2,29)))
#handles also standard month length
print(str(check_date(2016,3,31)))
print(str(check_date(2016,4,31)))
Run Code Online (Sandbox Code Playgroud)
False
True
False
True
False
Run Code Online (Sandbox Code Playgroud)
这是对 DhruvPathak 答案的改进,作为编辑更有意义,但它被拒绝为“此编辑旨在向帖子的作者发表意见,作为编辑没有任何意义。它应该写为评论或评论回答。 ”
小智 6
这个问题假设没有库的解决方案涉及“大量的 if 语句”,但它没有:
def is_valid_date(year, month, day):
day_count_for_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year%4==0 and (year%100 != 0 or year%400==0):
day_count_for_month[2] = 29
return (1 <= month <= 12 and 1 <= day <= day_count_for_month[month])
Run Code Online (Sandbox Code Playgroud)