python - 在Python中将带有时区的time_struct转换为日期时间GMT

标签 python date datetime

我正在从 Feedparser 检索 struct_time 日期。

如下所示,FeedParser 自动将日期解析为 GMT(第二行,EDT,从 19:19 转换为 23:19)

FeedParser 将 Sun, 06 Sep 2020 23:07:16 GMT 转换为 struct_time((2020, 9, 6, 23, 7, 16, 6, 250, 0))

FeedParser 将 Fri, 11 Sep 2020 19:19:01 EDT 转换为 struct_time((2020, 9, 11, 23, 19, 1, 4, 255, 0))

当我尝试使用以下内容将 struct_time 转换为日期时间时,我得到 GMT + 1(我的时区)。

from datetime import datetime
from time import mktime
datetime.fromtimestamp(mktime(struct_time((2020, 9, 6, 23, 7, 16, 6, 250, 0))))
> datetime.datetime(2020, 9, 7, 0, 7, 16)

如何将这些 struct_time 转换为日期时间 GMT?

最佳答案

要获取时区感知的日期时间对象,您可以将时间元组的相关部分解压到日期时间对象中,并将 tzinfo 属性设置为 UTC:

from datetime import datetime, timezone

# given a time_struct tuple like
s = (2020, 9, 6, 23, 7, 16, 6, 250, 0)
# convert to datetime object as
dt = datetime(*s[:6], tzinfo=timezone.utc)
print(dt)
>>> 2020-09-06 23:07:16+00:00

关于python - 在Python中将带有时区的time_struct转换为日期时间GMT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64012907/

相关文章:

python - 如何自动按计划运行 Google Cloud 的 "AI Notebooks"?

python - 我可以在 python 交互模式下有多个 matplotlib 绘图窗口吗?

xslt - 使用 XSLT/XPath 进行日期格式化

java - 我想将 "08:30:00"转换为 P00DT08H30M。在java中转换为所需输出的最佳方法是什么?

javascript - momentjs 如何处理以月或年为单位的加法或减法

Python/Pandas - 给定特定日期,查找列表中的前一个日期

python - 循环运行整个单元测试

javascript - 字符串到日期 - php iso 字符串格式

sql - 比较 SQL Server 中日期和日期时间的相等性

python - Pandas 用 groupby 划分两列