Parsing datetime strings with microseconds in Python 2.5

Manuel Ceron picture Manuel Ceron · Feb 10, 2009 · Viewed 12.8k times · Source

I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:

'2009-02-10 16:06:52.598800'

These strings were generated using str(datetime_object). The problem is that, for some reason, str(datetime_object) generates a different format when the datetime object has microseconds set to zero and some strings look like this:

'2009-02-10 16:06:52'

How can I parse these strings and convert them into a datetime object?

It's very important to get all the data in the object, including microseconds.

NOTE: I have to use Python 2.5, the format directive %f for microseconds doesn't exist in 2.5.

Answer

Eli Bendersky picture Eli Bendersky · Feb 10, 2009

Alternatively:

from datetime import datetime

def str2datetime(s):
    parts = s.split('.')
    dt = datetime.strptime(parts[0], "%Y-%m-%d %H:%M:%S")
    return dt.replace(microsecond=int(parts[1]))

Using strptime itself to parse the date/time string (so no need to think up corner cases for a regex).