1

我有一个 datetime 类型,我想将其转换为 int 但以毫秒为单位的精度。例如,我在 UTC 2018-11-19 02:19:53.497 中有日期时间,我希望它转换为 1542593993497

目前我写的函数如下:

def convert(inputDatetime):
    return int((inputDatetime - datetime.datetime(1970,1,1)).total_seconds())

这里的日期时间是以百万秒为单位的精度,例如 datetime.datetime(2009, 3, 20, 13, 55, 18, 993000)

该函数目前只能将日期时间转换为以秒为单位的 int 精度。我应该如何使精度以百万秒为单位?

我目前使用的 Python 版本是 2.7

4

1 回答 1

1

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

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

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

测试:

dt = datetime.datetime(2009, 3, 20, 13, 55, 18, 993000)
print("%d" % unix_time_millis(dt))  # 1237557318993

关键是计算(dt - epoch).total_seconds()应该以浮点格式返回秒(即包括毫秒),然后乘以 1000.0。

于 2018-11-19T02:56:41.317 回答