2010-02-03

Convert a time string (with microseconds) in a datetime

I struggled a bit with datetime & friends providing a strftime() that support %f (for microseconds output) but not a strptime() . That's really boring and counter-intuitive, and luckily it was fixed in 2.6:

$ python2.6
>>> import datetime
>>> datetime.datetime.strptime('22:57:39.101941', '%H:%M:%S.%f')
datetime.datetime(1900, 1, 1, 22, 57, 39, 101941)

but on my servers I still have 2.5, so what to do?

I found a reply on StackOverflow quite interesting:

$ python2.5
>>> from dateutil.parser import parser
>>> p = parser()
>>> p.parse('22:57:39.101941')
datetime.datetime(2010, 2, 3, 22, 57, 39, 101941)

ok, it uses the current date (instead of 1900-01-01) but it's still has the microseconds correctly recognized (and since I need a time diff, I'm fine with that).

1 comment:

Unknown said...

Thanks! It was very useful!