Correctly parse date string with timezone information

房东的猫 提交于 2019-12-12 10:55:36

问题


I'm receiving a formatted date string like this via the pivotal tracker API: "2012/06/05 17:42:29 CEST"

I want to convert this string to a UTC datetime object, it looks like python-dateutil does not recognize that timezone, pytz doesn't know it either.

I fear my best bet is to replace CEST in the string with CET, but this feels very wrong. Is there any other way to parse summer time strings to UTC datetime objects I couldn't find?

pytz.timezone('CEST')
# -> pytz.exceptions.UnknownTimeZoneError: 'CEST'
dateutil.parser.parse("2012/06/05 17:42:29 CEST")
# -> datetime.datetime(2012, 6, 5, 17, 42, 29)

Edit: After thinking about it again subtracting one hour is completely false as the corresponding timezone is also currently in summer time, the issue of parsing still stands


回答1:


There is no real CEST timezone. Use Europe/Paris, Europe/Berlin or Europe/Prague (or another one) according to your region:

>>> pytz.country_timezones('de')
[u'Europe/Berlin']

>>> pytz.country_timezones('fr')
[u'Europe/Paris']

They are (currently) identical and all referring to CEST in summer.

>>> dateutil.parser.parse("2012/06/05 17:42:29 CEST").astimezone(pytz.utc)
datetime.datetime(2012, 6, 5, 15, 42, 29, tzinfo=<UTC>)


来源:https://stackoverflow.com/questions/10913986/correctly-parse-date-string-with-timezone-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!