syntax-check with regular expressions?

Duncan Booth me at privacy.net
Tue Jul 27 14:22:24 CEST 2004


spamnews at gmx.de (Detlef Jockheck) wrote in 
news:b5a042c1.0407270400.13d9c94b at posting.google.com:

> Hi,
> 
> I would like to check if a string contains a valid date format
> (Format: "dd.mm.yyyy") or not.
> 
> What is the best way to do this. regexp? At the moment it would be
> sufficient to check for
> [digit][digit].[digit][digit].[digit][digit][digit][digit] but a full
> date verification (Month in range 1-12 ...) would be very nice too.
> 
> Sample code would help me very much.
> 
> regards
> Detlef
> 
> PS: I'm a python newbie, so excuse this silly question
> 
Don't use a regexp for this sort of task, its much better to do the 
conversion and catch an error if the conversion fails. In this case you 
should use time.strptime with an appropriate format. Sample code as 
requested:

>>> import time
>>> time.strptime("27.7.2004","%d.%m.%Y")
(2004, 7, 27, 0, 0, 0, 1, 209, -1)
>>> time.strptime("27.13.2004","%d.%m.%Y")

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in -toplevel-
    time.strptime("27.13.2004","%d.%m.%Y")
  File "C:\Python23\lib\_strptime.py", line 424, in strptime
    raise ValueError("time data did not match format:  data=%s  fmt=%s" %
ValueError: time data did not match format:  data=27.13.2004  fmt=%d.%m.%Y
>>> time.strptime("29.2.1800", "%d.%m.%Y")

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in -toplevel-
    time.strptime("29.2.1800", "%d.%m.%Y")
  File "C:\Python23\lib\_strptime.py", line 513, in strptime
    julian = datetime_date(year, month, day).toordinal() - \
ValueError: day is out of range for month
>>> time.strptime("29.2.2000", "%d.%m.%Y")
(2000, 2, 29, 0, 0, 0, 1, 60, -1)
>>> 




More information about the Python-list mailing list