add*_*ons 63 ruby python datetime epoch
我使用ruby脚本将iso时间戳转换为epoch,我正在解析的文件具有以下时间戳结构:
2009-03-08T00:27:31.807
Run Code Online (Sandbox Code Playgroud)
因为我想保持毫秒,我使用遵循ruby代码将其转换为纪元时间:
irb(main):010:0> DateTime.parse('2009-03-08T00:27:31.807').strftime("%Q")
=> "1236472051807"
Run Code Online (Sandbox Code Playgroud)
但在python我试过以下:
import time
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807))
Run Code Online (Sandbox Code Playgroud)
但我没有得到原来的时间日期时间,
>>> time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807))
'41152-03-29 02:50:07'
>>>
Run Code Online (Sandbox Code Playgroud)
我想知道它是如何格式化的?
fal*_*tru 118
用途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'
Run Code Online (Sandbox Code Playgroud)
%f指令仅受支持datetime.datetime.strftime,而不是由time.strftime.
更新替代使用%,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'
Run Code Online (Sandbox Code Playgroud)
Jor*_*ley 16
那些是毫秒,只需将它们除以1000,因为gmtime需要秒......
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90266 次 |
| 最近记录: |