使用“时间”库在python中从gmt转换为秒,从gmt返回至秒

时间:2019-11-01 15:56:34

标签: python python-3.x python-2.7 time 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。

1 个答案:

答案 0 :(得分:0)

在我的情况下(GMT + 9),我有9个小时的时差。

因此,我想您应该了解到自己的TZ和GMT之间的区别。

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