Date validation

Eric Brunel eric.brunel at pragmadev.com
Fri Apr 25 05:44:14 EDT 2003


James Gregory wrote:
> Hi all,
> 
> I'm writing a killer web app in python and I want to validate all the
> input it gets. Amongst said input are dates represented as text strings
> of the format 'YYYY-MM-DD' - how can I check whether or not such strings
> represent a valid date? I had thought that
> 
>     time.strptime('2003-4-31', '%Y-%m-%d')
> 
> would throw an exception (since gnome-something tells me that april only
> has 30 days), but it just gives me back
> 
>     (2003, 4, 31, 0, 0, 0, 3, 121, 0)
> 
> indeed I'm even able to use mktime on that without an exception.

And you even can to

 >>> tt = time.strptime('2003-4-31', '%Y-%m-%d')
 >>> t = time.mktime(tt)
 >>> print time.localtime(t)
(2003, 5, 1, 1, 0, 0, 3, 121, 1)

So just testing if you get the same day and month in your original one and the 
one returned by localtime may be enough.

BTW, allowing invalid dates in time tuples is in fact quite useful. For example, 
you can easily get the day after a given date by doing:

time.localtime(time.mktime((year, month, day+1, 0, 0, 0, 0, 0, -1)))

See:

 >>> time.localtime(time.mktime((2003, 2, 28+1, 0, 0, 0, 0, 0, -1)))
(2003, 3, 1, 0, 0, 0, 5, 60, 0)
 >>> time.localtime(time.mktime((2000, 2, 28+1, 0, 0, 0, 0, 0, -1)))
(2000, 2, 29, 0, 0, 0, 1, 60, 0)

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com





More information about the Python-list mailing list