Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 242
davidx1 Avatar asked Apr 03 '12 05:04

davidx1


People also ask

How do you check a date is valid or not in Python?

Python Program : split('/') isValidDate = True try: datetime. datetime(int(year), int(month), int(day)) except ValueError: isValidDate = False if(isValidDate): print("Input date is valid ..") else: print("Input date is not valid..")

How do you check if a date is valid?

Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.

How do you check if a string is a valid date?

Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.


2 Answers

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

like image 134
Roman A. Taycher Avatar answered Sep 19 '22 19:09

Roman A. Taycher


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)) 
like image 39
DhruvPathak Avatar answered Sep 19 '22 19:09

DhruvPathak