Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing datetime strings with microseconds in Python 2.5

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.

like image 374
Manuel Ceron Avatar asked Feb 10 '09 05:02

Manuel Ceron


People also ask

How do you write microseconds in Python?

Using %f with strftime() in Python to get microseconds.

How do I convert string time to milliseconds Python?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time. time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off.

How do I convert datetime to seconds in Python?

To convert a datetime to seconds, subtracts the input datetime from the epoch time. For Python, the epoch time starts at 00:00:00 UTC on 1 January 1970. Subtraction gives you the timedelta object. Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch.


2 Answers

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).

like image 200
Eli Bendersky Avatar answered Sep 19 '22 11:09

Eli Bendersky


Use the dateutil module. It supports a much wider range of date and time formats than the built in Python ones.

You'll need to easy_install dateutil for the following code to work:

from dateutil.parser import parser

p = parser()
datetime_with_microseconds = p.parse('2009-02-10 16:06:52.598800')
print datetime_with_microseconds.microsecond

results in:

598799
like image 26
Soviut Avatar answered Sep 19 '22 11:09

Soviut