Serializing / Unserializing datetime
Gerard Flanagan
grflanagan at yahoo.co.uk
Sun May 28 16:27:34 EDT 2006
Brendan wrote:
> Thanks John. I've discovered that datetime.strptime will be available
> in 2.5, (http://docs.python.org/dev/whatsnew/modules.html) but your
> example will work in the meantime.
>
> BJ
I don't think it's what you want but I had the following on file - it
uses time.strptime() which I didn't know there was a problem with. Not
tested beyond what you see.
--------------------------------------------------------------------------------
import time
import datetime
DDMMYY = ['%d %m %Y', '%d %m %y', '%d/%m/%Y', '%d/%m/%y', '%d-%m-%Y',
'%d-%m-%y' ]
def yearmonthday(datestring, fmts=DDMMYY):
ymd = None
for f in fmts:
try:
ymd = time.strptime( datestring, f )
break
except ValueError:
continue
if ymd is None:
raise ValueError
return ymd[0], ymd[1], ymd[2]
def is_valid_date(datestring, fmts=DDMMYY):
try:
yearmonthday(datestring, fmts)
return True
except ValueError:
return False
def string_to_date(datestring, fmts=DDMMYY):
return datetime.date( *yearmonthday(datestring, fmts) )
assert string_to_date( '1/2/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1 2 01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '01/02/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1/02/2001', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '29/02/2008', DDMMYY) ==
datetime.date(2008,2,29)
assert string_to_date( '01/2/99', DDMMYY) == datetime.date(1999,2,1)
for d in [ '', '32/1/01', '01/13/01', '29/2/07', '1/2', 'abcdef' ]:
assert not is_valid_date(d, DDMMYY)
------------------------------------------------------------------------------------
Gerard
More information about the Python-list
mailing list