以毫秒为单位将纪元时间转换为日期时间

我使用了一个 Ruby 脚本将 iso 时间戳转换为 epoch,我解析的文件具有以下时间戳结构:

2009-03-08T00:27:31.807

因为我想保持毫秒,所以我用下面的 Ruby 代码将其转换为纪元时间:

irb(main):010:0> DateTime.parse('2009-03-08T00:27:31.807').strftime("%Q")
=> "1236472051807"

但是在 python 中,我试着这样做:

import time
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807))

但是我没有拿回原始时间,

>>> time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807))
'41152-03-29 02:50:07'
>>>

我想知道它是否与我如何格式化有关?

158130 次浏览

those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

I'm a pendulum fan... so...

import pendulum
pendulum.from_timestamp(1236472051807/1000.0,tz='America/Toronto')

outputs:

DateTime(2019, 12, 20, 10, 55, 10, tzinfo=Timezone('America/Toronto'))

For all the searches looking for internalDate for the Gmail API... the above is what works for me and is more accurate than the Date header.