在python中,如何检查日期是否有效? [英] In python, how to check if a date is valid?

查看:811
本文介绍了在python中,如何检查日期是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一种日历网络应用程序



我已经在HTML中设置了以下表单

 < form action ='/ event'method ='post'> 
年(yyyy):< input type ='text'name ='year'/>
月(mm):< input type ='text'name ='month'/>
Day(dd):< input type ='text'name ='day'/>
小时(hh):< input type ='text'name ='hour'/>
说明:< input type ='text'name ='info'/>
< input type ='submit'name ='submit'value ='提交'/>
< / form>

然后将用户的输入提交到cherrypy服务器



我想知道,有没有办法检查用户输入的日期是否为有效日期?



显然我可以写一个整体很多if语句,但是有没有内置的函数可以检查这个?



谢谢

解决方案

你可以尝试做

  import datetime 
datetime.datetime(year = year, month = month,day = day,hour = hour)

小时> 23,不存在的闰年(月= 2 on has max max max max max max max max,,,))))))))))))))))))))))))))))))) b $ b

此外,您可以尝试将其与一些理智的上下限进行比较。
ex。:

  datetime.date(year = 2000,month = 1,day = 1) datetime.datetime(year = year,month = month,day = day,hour = hour)< = datetime.datetime.now()

相关的上下限权限取决于您的需求。



编辑:请记住,这不会处理某些datetimes可能不会适用于您的申请(最小生日,节假日,营业时间以外等等)


I am building a kind of calender web app

I have set up the following form in 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>

The input from the user is then submited in the a cherrypy server

I am wondering, is there a way to check if the date entered by the user is a valid date?

Obviously I could write a whole lot of if statements, but are there any built in function that can check this?

Thanks

解决方案

You could try doing

import datetime
datetime.datetime(year=year,month=month,day=day,hour=hour)

that will eliminate somethings like months >12 , hours > 23, non-existent leapdays (month=2 has max of 28 on non leap years, 29 otherwise, other months have max of 30 or 31 days)(throws ValueError exception on error)

Also you could try to compare it with some sanity upper/lower bounds. ex.:

datetime.date(year=2000, month=1,day=1) < datetime.datetime(year=year,month=month,day=day,hour=hour) <= datetime.datetime.now()

The relevant upper and lower sanity bounds depend on your needs.

edit: remember that this does not handle certain datetimes things which may not be valid for your application(min birthday, holidays, outside hours of operation, ect.)

这篇关于在python中,如何检查日期是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆