Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime to microtime

I've looked all around, and there seem to be a lot of hacks, but no simple, "good" ways to do this. I want to convert a Python datetime object into microtime like time.time() returns (seconds.microseconds).

What's the best way to do this? Using mktime() strips off the microseconds altogether, you could conceivably build up a timedelta, but that doesn't seem right. You could also use a float(strftime("%s.%f")) (accounting for rounding seconds properly), but that seems like a super-hack.

What's the "right" way to do this?

like image 300
Taj Morton Avatar asked Aug 30 '11 02:08

Taj Morton


People also ask

How do you convert datetime to milliseconds?

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .

How do you convert datetime to epoch in Python?

Using strftime() to convert Python datetime to epoch strftime() is used to convert string DateTime to DateTime. It is also used to convert DateTime to epoch. We can get epoch from DateTime from strftime().

How do you get milliseconds after epoch Python?

To get the current time in milliseconds in Python: Import time module. Get the current epoch time. Multiply the current epoch time by 1000.


2 Answers

time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0 

works if you don't want to use strftime and float.

It returns the same thing as time.time() with dt = datetime.datetime.now().

like image 141
agf Avatar answered Nov 02 '22 17:11

agf


def microtime(dt):
    unixtime = dt - datetime.datetime(1970, 1, 1)
    return unixtime.days*24*60*60 + unixtime.seconds + unixtime.microseconds/1000000.0
like image 40
Mark Ransom Avatar answered Nov 02 '22 18:11

Mark Ransom