Taj Morton
Taj Morton

Reputation: 1638

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?

Upvotes: 5

Views: 7218

Answers (3)

user3825463
user3825463

Reputation: 1

import time;

microtime=int(time.time()*1000);

print microtime;

Upvotes: -1

agf
agf

Reputation: 176930

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

Upvotes: 8

Mark Ransom
Mark Ransom

Reputation: 308482

def microtime(dt):
    unixtime = dt - datetime.datetime(1970, 1, 1)
    return unixtime.days*24*60*60 + unixtime.seconds + unixtime.microseconds/1000000.0

Upvotes: 2

Related Questions