python linux时间戳到日期时间和反向

标签 python python-3.3

<分区>

我想知道如何将日期时间 Wed Apr 24 19:25:06 2013 GMT 转换为 Linux 时间戳 1366831506000 (13 digits)] 并使用 python 反转。

例如:

Wed Apr 24 19:25:06 2013 GMT

1366831506000

1366831506000

Wed Apr 24 19:25:06 2013 GMT

最佳答案

从字符串到时间戳,使用time.strptime() ,将生成的 struct_time 元组传递给 time.mktime() ;您的时间戳使用毫秒,而不是 UNIX 秒浮点值,因此您需要乘以 1000:

import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr, "%a %b %d %H:%M:%S %Y %Z")) * 1000

在另一个方向,使用time.strptime() ,传入由 time.gmtime() 创建的 struct_time 元组,首先将时间戳除以 1000:

timestamp = 1366831506000
time.strftime("%a %d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 1000.0))

演示:

>>> datestr = "Wed Apr 24 19:25:06 2013 GMT"
>>> time.mktime(time.strptime(datestr, "%a %b %d %H:%M:%S %Y %Z")) * 1000
1366827906000.0
>>> timestamp = 1366831506000
>>> time.strftime("%a %d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 1000.0))
'Wed 24 Apr 2013 19:25:06 GMT'

关于python linux时间戳到日期时间和反向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198606/

相关文章:

python - 如何在带有数据帧的字典中使用 if/else?

python - 如何从我的模块导入和创建我的类?

python多处理从多处理队列访问数据不读取所有数据

python - 在 Python 2.7 中高效读取 800 GB XML 文件

python - PyQT:在第一个窗口之前退出/完成第二个窗口

python - 网络 cookies

python - 计算平方根的逻辑思维

python - 在 python 3 中处理多个字符集

python - 在 Python 中迭代 OrderedDict

Python 列表变成字典?