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时间戳转换为epoch,我正在解析的文件有以下时间戳结构:
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?
我想知道它是否与我的格式有关?
2 个解决方案
#1
94
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'
%f
directive is only supported by datetime.datetime.strftime
, not by time.strftime
.
%f指令仅受datetime.datetime支持。由time.strftime strftime,不是。
UPDATE Alternative 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'
#2
13
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))
#1
94
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'
%f
directive is only supported by datetime.datetime.strftime
, not by time.strftime
.
%f指令仅受datetime.datetime支持。由time.strftime strftime,不是。
UPDATE Alternative 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'
#2
13
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))