gpt4 book ai didi

python - 如何在 Python 中将日期时间转换为 UTC 时间戳?

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:29 25 4
gpt4 key购买 nike

来自 http://docs.python.org/library/time.html :

time.mktime(t): This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.

这表示您需要以本地时间而不是 UTC 指定时间元组。但是,我想在 UTC 中指定;我不想在盒子上使用本地时区。

有什么方法可以让我从日期时间转到时间戳,时间被视为 UTC?当我与时间戳相互转换时,我希望能够将所有内容都保留为规范化的 UTC 形式(日期时间对象)。

我希望能够做这样的事情并让 x 和 y 的结果相同:

 y = datetime.datetime.utcfromtimestamp(time.mktime(x.timetuple()))
x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')
stamp = time.mktime(x.timetuple())
y = datetime.datetime.utcfromtimestamp(stamp)
x
datetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc())
y
datetime.datetime(2010, 10, 28, 6, 17)

最佳答案

我认为您正在寻找 calendar.timegm:

import datetime
import dateutil.parser
import calendar

x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')
stamp = calendar.timegm(x.timetuple())
y = datetime.datetime.utcfromtimestamp(stamp)
print(repr(x))
# datetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc())

print(repr(y))
# datetime.datetime(2010, 10, 27, 22, 17)

关于python - 如何在 Python 中将日期时间转换为 UTC 时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4046401/

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