How can I convert a datetime object to milliseconds since epoch (unix time) in Python?
In Python 3.3, added new method timestamp
:
import datetimeseconds_since_epoch = datetime.datetime.now().timestamp()
Your question stated that you needed milliseconds, which you can get like this:
milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
If you use timestamp
on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.
>>> import datetime>>> # replace datetime.datetime.now() with your datetime object>>> int(datetime.datetime.now().strftime("%s")) * 1000 1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time>>> # replace datetime.datetime.now() with your datetime object>>> time.mktime(datetime.datetime.now().timetuple()) * 10001312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation: