将具有毫秒的时期转换为日期时间 [英] converting epoch time with milliseconds to datetime
问题描述
2009-03-08T00:27:31.807
由于我想保持毫秒,红宝石代码将其转换为时代:
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'
>>>
我想知道这与我的格式化有关吗?
使用 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
指令仅由 datetime.datetime.strftime
,而不是 time.strftime
。
更新使用 %
, str.format
:
>>>进口时间
>>>> 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 have used a ruby script to convert iso time stamp to epoch, the files that I am parsing has following time stamp structure:
2009-03-08T00:27:31.807
Since I want to keep milliseconds I used following ruby code to convert it to epoch time:
irb(main):010:0> DateTime.parse('2009-03-08T00:27:31.807').strftime("%Q")
=> "1236472051807"
But In python I tried following:
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?
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'
这篇关于将具有毫秒的时期转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!