In python, how to check if a date is valid?

2019-01-14 21:33发布

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

8条回答
聊天终结者
2楼-- · 2019-01-14 22:13

Here is a solution using time.

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
查看更多
在下西门庆
3楼-- · 2019-01-14 22:14

The question assumes that the solution without libraries involves "a whole lot of if statements", but it does not:

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])
查看更多
老娘就宠你
4楼-- · 2019-01-14 22:20

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

查看更多
虎瘦雄心在
5楼-- · 2019-01-14 22:21

You can try using datetime and handle the exceptions to decide valid/invalid date : Example : http://codepad.org/XRSYeIJJ

import datetime
correctDate = None
try:
    newDate = datetime.datetime(2008,11,42)
    correctDate = True
except ValueError:
    correctDate = False
print(str(correctDate))
查看更多
倾城 Initia
6楼-- · 2019-01-14 22:25

You can try using datetime and handle the exceptions to decide valid/invalid date:

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

This is improvement of an answer by DhruvPathak and makes more sense as an edit but it was rejected as "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."

查看更多
祖国的老花朵
7楼-- · 2019-01-14 22:32

Use datetime

eg.

>>> 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
查看更多
登录 后发表回答