我正在构建一种日历web应用程序
我在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>
然后在cherrypy服务器中提交来自用户的输入
我想知道,有没有办法检查用户输入的日期是否有效?
显然,我可以写一大堆if语句,但是有没有内置的函数可以检查呢?
谢谢
发布于 2012-04-03 14:08:06
你可以试着做
import datetime
datetime.datetime(year=year,month=month,day=day,hour=hour)
这将消除月份>12,小时> 23,不存在的闰日(month=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()
相关的合理上限和下限取决于您的需求。
编辑:请记住,这不会处理某些日期时间的事情,这些事情对你的应用程序可能是无效的(最小的生日,假日,工作时间以外的时间,等等)。
发布于 2012-04-03 14:39:37
您可以尝试使用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))
发布于 2018-08-23 16:40:35
这个问题假设没有库的解决方案涉及“大量的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])
https://stackoverflow.com/questions/9987818
复制相似问题