首页 > 解决方案 > 使用“时间”库在 python 中到 gmt 和从 gmt 返回到秒的秒数

问题描述

对于以下代码,我希望 seconds_input 和 seconds_output 相同。但我得到一个小时的差异:

import time

seconds_input = 1571875186
date_struct1 = time.gmtime(seconds_input)

tm_str = time.strftime("%Y-%m-%d %H:%M:%S", date_struct1)
date_struct2 = time.strptime(tm_str, '%Y-%m-%d %H:%M:%S')
seconds_output = time.mktime(date_struct2)

print(seconds_input - seconds_output)
print(date_struct1, date_struct2)

我认为这可能是由于tm_isdst=-1在 中date_struct2,但我不确定如何将其设置为0.

我已经尝试过date_struct2.tm_isdst = 0,但出现以下错误:

AttributeError: readonly attribute

更新:

如果 seconds_input 对应于未来的日期,那么 seconds_input 和 seconds_output 将是相同的。

例如,如果 seconds_input = 1673084786。

标签: pythonpython-3.xpython-2.7timegmt

解决方案


就我而言(GMT+9),我有 9 小时的差异。

所以我想你得到了你自己的 TZ 和 GMT 之间的区别——就像它应该的那样。

要正确转换,您必须添加(或减去)3600 秒,即 1 小时。


推荐阅读