How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

SuperString picture SuperString · Aug 9, 2011 · Viewed 427.6k times · Source

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.

How do I do this?

Answer

Sophie Alpert picture Sophie Alpert · Jun 20, 2012

It appears to me that the simplest way to do this is

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0