Python 以毫秒为单位将纪元时间转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21787496/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting epoch time with milliseconds to datetime
提问by add-semi-colons
I have used a ruby script to convert iso time stamp to epoch, the files that I am parsing has following time stamp structure:
我使用 ruby 脚本将 iso 时间戳转换为纪元,我正在解析的文件具有以下时间戳结构:
2009-03-08T00:27:31.807
Since I want to keep milliseconds I used following ruby code to convert it to epoch time:
由于我想保持毫秒,我使用以下 ruby 代码将其转换为纪元时间:
irb(main):010:0> DateTime.parse('2009-03-08T00:27:31.807').strftime("%Q")
=> "1236472051807"
But In python I tried following:
但在 python 中,我尝试了以下操作:
import time 
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807))
But I don't get the original time date time back,
但我没有得到原来的时间日期时间,
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807))
'41152-03-29 02:50:07'
>>> 
I wonder is it related to how I am formatting?
我想知道它与我的格式化方式有关吗?
采纳答案by falsetru
Use datetime.datetime.fromtimestamp:
使用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'
%fdirective is only supported by datetime.datetime.strftime, not by time.strftime.
%f指令仅受 支持datetime.datetime.strftime,不受time.strftime.
UPDATEAlternative using %, str.format:
更新替代使用%, 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'
回答by Joran Beasley
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
这些是毫秒,只需将它们除以 1000,因为 gmtime 需要秒......
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))

