python
  • validation
  • date
  • time
  • 2012-04-03 111 views 15 likes 
    15

    我建立了一种压光机的Web应用程序的在Python中,如何检查日期是否有效?

    我已经建立了以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的服务器submited

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

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

    感谢

    +0

    相关:[我如何验证python中的日期字符串格式?](http://stackoverflow.com/q/16870663) – kenorb 2015-07-27 20:35:15

    回答

    18

    你可以尝试做

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

    将消除象个月出头> 12小时> 23,不存在leapdays(月= 2有28最大非闰年,29,否则,其他月份最多有30天或31天)(错误时抛出ValueError异常)

    也可以尝试将它与一些理智上/下限进行比较。 ex .:

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

    相关的上限和下限理智范围取决于您的需求。

    编辑:记住,这不处理某些日期时间的东西可能不是有效的应用程序

    3

    使用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 
    
    +0

    但是,这不会给我一个错误消息?并导致一切有点崩溃?我希望是否有一个函数用于检验,如果是有效日期则返回1,如果无效则返回0。然后我可以提示用户重新输入日期到网页中。 – Synia 2012-04-03 06:13:50

    +1

    或者你可以'尝试...除了'并且发现错误。然后,你可以做你想做的事情,如果你选择了,就默默地传递错误。 – jamylak 2012-04-03 06:15:00

    +1

    请参阅http://docs.python.org/tutorial/errors.html#handling-exceptions – 2012-04-03 06:17:54

    21

    您可以尝试使用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)) 
    
    -1

    所以,这里是我的哈克的解决方案来修正提供无效的日期。这假定用户从提供第1-31天的通用html表单提交作为选项。主要问题是用户提供一个月不存在的一天(例如9月31日)

    def sane_date(year, month, day): 
        # Calculate the last date of the given month 
        nextmonth = datetime.date(year, month, 1) + datetime.timedelta(days=35) 
        lastday = nextmonth.replace(day=1) - datetime.timedelta(days=1) 
        return datetime.date(year, month, min(day, lastday.day)) 
    
    class tests(unittest.TestCase): 
    
        def test_sane_date(self): 
         """ Test our sane_date() method""" 
         self.assertEquals(sane_date(2000,9,31), datetime.date(2000,9,30)) 
         self.assertEquals(sane_date(2000,2,31), datetime.date(2000,2,29)) 
         self.assertEquals(sane_date(2000,1,15), datetime.date(2000,1,15)) 
    
    1

    这是一个使用时间的解决方案。

    import time 
    def is_date_valid(year, month, day): 
        this_date = '%d/%d/%d' % (month, day, year) 
        try: 
         time.strptime(this_date, '%m/%d/%Y') 
        except ValueError: 
         return False 
        else: 
         return True 
    
    +1

    你为什么要这样做,而不是只是'日期(年,月,日)'? – jfs 2015-12-04 18:12:19

    1

    您可以尝试使用datetime和处理异常,决定有效/无效日期:

    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))) 
    

    gives

    False 
    True 
    False 
    True 
    False 
    

    这是an answer by DhruvPathak改进和更有意义作为编辑,但它被拒绝为“This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer.

    相关问题