Janus Troelsen
Janus Troelsen

Reputation: 21298

How to parse time.time()?

I see how How can I parse a time string containing milliseconds in it with python? provides a solution when parsing a full timestamp and Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch? provides a solution when parsing time.gmtime(). How do I parse time.time()? That means, converting it to a time tuple, or something similar with better precision.

I was hoping to preserve microseconds.

Upvotes: 1

Views: 745

Answers (2)

Travis Vaught
Travis Vaught

Reputation: 358

There is a long history of discussion on the python bug tracker about round-tripping timestamps. It's probably worth a read, but the quick hack is:

In [1]: import datetime, time

In [2]: dt = datetime.datetime(2012, 2, 10, 15, 18, 15, 234567)

In [3]: seconds = time.mktime(dt.timetuple())

In [4]: seconds += (dt.microsecond/1000000.0)

In [5]: seconds
Out[5]: 1328908695.234567

In [6]: datetime.datetime.fromtimestamp(seconds)
Out[6]: datetime.datetime(2012, 2, 10, 15, 18, 15, 234567)

Then, you may just deal with a datetime object which will allow you to parse things properly.

Upvotes: 1

Related Questions