Serializing / Unserializing datetime

John Machin sjmachin at lexicon.net
Sun May 28 01:52:20 CEST 2006


On 28/05/2006 3:37 AM, Brendan wrote:
> Hi All
> 
> I can't find the "Python Way" of writing a datetime instance to a
> string so that it can be easily parsed back again.  time.strptime is
> apparantly not supported on some platforms, and time.time <==>
> datetime.utcfromtimestamp will cause problems come 2038.  Unfortunately
> there don't seem to be "fromstring" equivalents for datetime.ctime or
> datetime.isoformat.
> 
> Ideally the serialized datetime should be human readable, and
> potentially parseable from other languages.  Any suggestions?
> 
>

It's not that hard to DIY; the simple code at the end of this posting 
(1) handles fractions of a second [which you may or may not want] 
without burdening the network or the readers' eyeballs with excess 
trailing zeroes (2) doesn't handle TZs [which you may or may not want].

Some further validation on input strings may be a good idea, if you need 
to eat other software's strings as well as yours. E.g. check that where 
the '-' characters should be that you find nothing stranger than '.' or 
'/'; certainly not digits.

HTH,
John

8<---
import datetime

def datetime_from_str(s):
     # YYYY-MM-DD HH:MM:SS.TTT
     # 01234567890123456789012
     year = int(s[0:4])
     month = int(s[5:7])
     day = int(s[8:10])
     hour = int(s[11:13])
     minute = int(s[14:16])
     microseconds = int(float(s[17:]) * 1000000.0)
     second, microsecond = divmod(microseconds, 1000000)
     return datetime.datetime(year, month, day, hour, minute, second, 
microsecond)

def datetime_as_str(dtm):
     part1 = dtm.strftime("%Y-%m-%d %H:%M:%S")
     micros = dtm.microsecond
     if not micros:
         return part1
     part2 = (".%06d" % micros).rstrip('0')
     return part1 + part2

if __name__ == "__main__":
     tests = [
         '1999-12-31 23:59:59.999999',
         '1999-12-31 23:59:59.99999999',
         '1999-12-31 23:59:59.999',
         '1999-12-31 23:59:59',
         '2000-01-01 00:00:00.000',
         '2000-01-01 00:00:00',
         '2000-01-01 00:00:00.000001',
         '2000-01-01 00:00:00.001',
         ]
     for test in tests:
         dtm = datetime_from_str(test)
         print "input str: ", repr(test)
         print "datetime:  ", repr(dtm)
         round_trip = datetime_as_str(dtm)
         print "output str:", repr(round_trip), ["not same", 
""][round_trip == test]
         print
8<---




More information about the Python-list mailing list