将时间戳自纪元转换为 datetime.datetime [英] Convert timestamp since epoch to datetime.datetime

查看:69
本文介绍了将时间戳自纪元转换为 datetime.datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自纪元以来,我有以下时间戳:

时间戳13461147179721354087827000

如何将这些时间戳转换为某些特定的输出格式,例如 mm/dd/yyyy hr:min:sec?

我试图将它们转换为 datetime.datetime 但它失败了:

<代码> >>>datetime.datetime.fromtimestamp(1346114717972)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:时间戳超出平台 time_t 的范围

我该怎么做?

解决方案

我会使用 time 模块

<预><代码>>>>导入时间>>>time.gmtime(1346114717972/1000.)time.struct_time(tm_year=2012, tm_mon=8, tm_mday=28, tm_hour=0, tm_min=45, tm_sec=17, tm_wday=1, tm_yday=241, tm_isdst=0)

这显示了 UTC/GMT 时间的时间戳.

时间戳除以 1000,因为您提供的戳记是自纪元以来的 毫秒,而不是秒.

然后使用 strftime 来格式化:

<预><代码>>>>time.strftime('%m/%d/%Y %H:%M:%S', time.gmtime(1346114717972/1000.))'08/28/2012 00:45:17'

I have the following timestamps since epoch:

Timestamp
1346114717972
1354087827000

How can I convert these timestamps to some specific output format, e.g., mm/dd/yyyy hr:min:sec?

I have tried to convert them to datetime.datetime but it failed:

 >>> datetime.datetime.fromtimestamp(1346114717972)
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 ValueError: timestamp out of range for platform time_t

How can I do this?

解决方案

I would use the time module

>>> import time
>>> time.gmtime(1346114717972/1000.)
time.struct_time(tm_year=2012, tm_mon=8, tm_mday=28, tm_hour=0, tm_min=45, tm_sec=17, tm_wday=1, tm_yday=241, tm_isdst=0)  

This shows the timestamp in UTC/GMT time.

The timestamp is divided by 1000 as the stamps you have provided are in milliseconds since the epoch, not seconds.

Then use strftime to format like so:

>>> time.strftime('%m/%d/%Y %H:%M:%S',  time.gmtime(1346114717972/1000.))
'08/28/2012 00:45:17'

这篇关于将时间戳自纪元转换为 datetime.datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆