如何在 Python 中将日期时间对象转换为自纪元(unix 时间)以来的毫秒数?

问题描述:

我有一个 Python datetime 对象,我想将其转换为 Unix 时间,或自 1970 年以来的秒/毫秒.

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

我该怎么做?

在我看来,最简单的方法是

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