如何创建不根据本地时间调整的 Unix 时间戳?

发布于 2024-09-10 17:28:24 字数 1074 浏览 4 评论 0 原文

所以我有 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 是否安全。

So I have datetime objects in UTC time and I want to convert them to UTC timestamps. The problem is, time.mktime makes adjustments for localtime.

So here is some code:

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())

Here is some output:

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

So obviously if the system is in UTC time no problem, but when it's not, it is a problem. Setting the environment variable and calling time.tzset works but is that safe? I don't want to adjust it for the whole system.

Is there another way to do this? Or is it safe to call time.tzset this way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静水深流 2024-09-17 17:28:24

calendar 模块包含 calendar.timegm 解决了这个问题。

calendar.timegm(tuple)

一个不相关但方便的函数,它需要一个时间元组,例如由 gmtime() 函数返回的时间元组。 html#module-time" rel="noreferrer">time 模块,并返回相应的 Unix 时间戳值,假设纪元为 1970 年,采用 POSIX 编码。事实上, time.gmtime()timegm() 是彼此的逆。

The calendar module contains calendar.timegm which solves this problem.

calendar.timegm(tuple)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文