Date validation

Andrew Bennetts andrew-pythonlist at puzzling.org
Fri Apr 25 03:34:44 EDT 2003


On Fri, Apr 25, 2003 at 05:22:51PM +1000, 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.
> 
> The docs for time.strptime inform me that it's libc's fault, which it
> probably is, but I'm still stuck for a method to validate this data.

In Python 2.3, strptime has been implemented independently of the platform
libc, and it does raise an exception:

    >>> import time
    >>> time.strptime('2003-4-31', '%Y-%m-%d')
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "/usr/lib/python2.3/_strptime.py", line 496, in strptime
        julian = datetime_date(year, month, day).toordinal() - \
    ValueError: day is out of range for month
    >>> 

You could try stealing Python 2.3's _strptime.py, or use the recipie at:
    
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/56036

They appear to be the same code anyway :)

-Andrew.






More information about the Python-list mailing list