如何将未知时区的字符串datetime转换为python中的时间戳 [英] how to convert a string datetime with unknown timezone to timestamp in python
问题描述
我有这样的日期时间 Thu Jun 02 11:56:53 CDT 2011
我试图使用下面的代码将其转换为datetime对象
I have a datetime like this Thu Jun 02 11:56:53 CDT 2011
I tried to convert it to datetime object using the code below
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
修复此问题吗?
There is no warning when I use UTC
instead of CDT
.
Can I use tzinfos
to fix this ?
推荐答案
简短的答案,不使用tzinfos,将CDT替换为等效的UTC:
Short answer, without using tzinfos, replace CDT with its UTC equivalent:
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)或抵消的秒数,这是文档:
You can use tzinfos, it must be a dict where keys are the unknows timezones and values are either string UTC format (UTC-5 for example) or number of seconds to offset, here is the doc:
TZINFOS
字符串中可能存在的其他时区名称/别名。此参数将时区名称(以及从这些时区偏移
)映射到时区。此参数可以是带有时区别名的
字典,该别名将时区名称映射到时区
,或者是带有两个参数(tzname和tzoffset)的函数,而
返回时区。名称映射到的时区可以
是相对于UTC的整数偏移量(以秒为单位)或tzinfo对象。如果设置了ignoretz,则将忽略此
参数。
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.
我尝试了两种方法并进行了比较
I tried with both methods and compared
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时必须反转符号(纠正我,这可能是相反的事情)
it seems like you have to inverse the sign when using tzinfos (correct me, it might be the inverse thing to do)
这篇关于如何将未知时区的字符串datetime转换为python中的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!