python
  • validation
  • date
  • time
  • 2012-04-03 104 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.

    相關問題