python – 如何创建不调整本地时间的unix时间戳?
作者:互联网
所以我有UTC时间的日期时间对象,我想将它们转换为UTC时间戳.问题是,time.mktime会对本地时间进行调整.
所以这里有一些代码:
import os
import pytz
import time
import datetime
epoch = pytz.utc.localize(datetime.datetime(1970, 1, 1))
print time.mktime(epoch.timetuple())
os.environ['TZ'] = 'UTC+0'
time.tzset()
print time.mktime(epoch.timetuple())
这是一些输出:
Python 2.6.4 (r264:75706, Dec 25 2009, 08:52:16)
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import pytz
>>> import time
>>> import datetime
>>>
>>> epoch = pytz.utc.localize(datetime.datetime(1970, 1, 1))
>>> print time.mktime(epoch.timetuple())
25200.0
>>>
>>> os.environ['TZ'] = 'UTC+0'
>>> time.tzset()
>>> print time.mktime(epoch.timetuple())
0.0
所以很明显,如果系统在UTC时间没有问题,但是当它不是时,这是一个问题.设置环境变量并调用time.tzset有效但是安全吗?我不想为整个系统调整它.
还有另一种方法吗?或者以这种方式调用time.tzset是安全的.
解决方法:
日历模块包含calendar.timegm
,可以解决此问题.
calendar.timegm(元组)
An unrelated but handy function that takes a time tuple such as returned by the
gmtime()
function in the 07001 module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, 07002 and 07003 are each others’ inverse.
标签:python,timezone,pytz 来源: https://codeday.me/bug/20190518/1129854.html