使用 'time' 库在 python 中到 gmt 的秒数和从 gmt 回到秒数

Seconds to gmt and from gmt back to seconds in python using 'time' library

对于以下代码,我希望 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)

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

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

AttributeError: readonly attribute

更新:

如果seconds_input对应的是未来的日期,那么seconds_input和seconds_output就是一样的。

例如 seconds_input = 1673084786.

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

所以我想你已经明白了你自己的 TZ 和 GMT 之间的区别——正如它应该的那样。

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