gpt4 book ai didi

python - 如何创建不针对本地时间进行调整的 unix 时间戳?

转载 作者:太空狗 更新时间:2023-10-30 01:03:55 24 4
gpt4 key购买 nike

所以我有 UTC 时间的 datetime 对象,我想将它们转换为 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 模块包含calendar.timegm这解决了这个问题。

calendar.timegm(元组)

An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.

关于python - 如何创建不针对本地时间进行调整的 unix 时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315092/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com