gpt4 book ai didi

python - 如何将未知时区的字符串datetime转换为python中的时间戳

转载 作者:行者123 更新时间:2023-11-28 21:36:19 26 4
gpt4 key购买 nike

我有这样的日期时间Thu Jun 02 11:56:53 CDT 2011我尝试使用下面的代码将其转换为datetime对象

from dateutil import parser
timestamp = parser.parse("Thu Jun 02 11:56:53 CDT 2011")

但是我得到这个警告
UnknownTimezoneWarning: tzname CDT identified but not understood. 
Pass `tzinfos` argument in order to correctly return a timezone-aware datetime.
In a future version, this raise an exception.
category=UnknownTimezoneWarning)

当我使用 UTC而不是 CDT时,没有警告。
我可以使用 tzinfos修复此问题吗?

最佳答案

简短的答案,不使用tzinfos,将CDT替换为其等效的UTC:

In [15]: from dateutil import parser
...: timestamp = parser.parse("Thu Jun 02 11:56:53 UTC-5 2011")
...:
...:

In [16]: timestamp
Out[16]: datetime.datetime(2011, 6, 2, 11, 56, 53, tzinfo=tzoffset(None, 18000))

您可以使用tzinfos,它必须是一个dict,其中键是未知时区,值是字符串UTC格式(例如,UTC-5)或要偏移的秒数,这是doc:

TZINFOS

Additional time zone names / aliases which may be present in the string. This argument maps time zone names (and optionally offsets from those time zones) to time zones. This parameter can be a dictionary with timezone aliases mapping time zone names to time zones or a function taking two parameters (tzname and tzoffset) and returning a time zone. The timezones to which the names are mapped can be an integer offset from UTC in seconds or a tzinfo object. This parameter is ignored if ignoretz is set.



我尝试了两种方法并进行了比较
timestamp = parser.parse("Thu Jun 02 11:56:53 CDT 2011", tzinfos={"CDT": -5*3600})
timestamp2 = parser.parse("Thu Jun 02 11:56:53 CDT 2011", tzinfos={"CDT": "UTC-5"})
timestamp3 = parser.parse("Thu Jun 02 11:56:53 UTC-0500 2011")

它打印
2011-06-02 11:56:53-05:00
2011-06-02 11:56:53-05:00
2011-06-02 11:56:53+05:00

看来您在使用tzinfos时必须要反转符号(对我来说,这可能是相反的事情)

关于python - 如何将未知时区的字符串datetime转换为python中的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51206500/

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