问题
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