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

106,556

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

You can try using dateutil.parser module for easier date parsing:

from dateutil.parser import parse
def is_valid_date(date):
    if date:
        try:
            parse(date)
            return True
        except:
            return False
    return False

Hope this helps.

Solution 5

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
Share:
106,556
davidx1
Author by

davidx1

Updated on June 30, 2021

Comments

  • davidx1
    davidx1 almost 3 years

    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

  • davidx1
    davidx1 about 12 years
    But wouldn't that give me an error message? and cause everything to kinda crash? I was hoping if there is a function which for exampel, returns 1 if it's valid date, and returns 0 if it's invalid. Then I can prompt the user to re-enter the date into the webpage.
  • jamylak
    jamylak about 12 years
    Or you could try...except and catch the error. Then you can do what you want, pass the error silently if you chose to.
  • jfs
    jfs over 8 years
    why would you do it instead of just date(year, month, day)?
  • NIMISHAN
    NIMISHAN over 5 years
    better provide some explanation
  • hellow
    hellow over 5 years
    While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find how to write a good answer very helpful. Please edit your answer.