7

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

Martin Thoma
  • 91,837
  • 114
  • 489
  • 768
Strayer
  • 2,820
  • 2
  • 24
  • 34
  • I'm not sure DST counts as a separate time zone for the purposes of date-time calculation. The date-time library should figure out whether DST applies for the given input and parse it correctly, I'd hope. – millimoose Jun 06 '12 at 12:15

1 Answers1

10

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>)
eumiro
  • 179,099
  • 29
  • 277
  • 252
  • Thing is that dateutil creates an naive datetime object for me: ValueError: astimezone() cannot be applied to a naive datetime – Strayer Jun 06 '12 at 12:25
  • 2
    @Strayer - if you know you're dealing with CET/CEST only, you can `.replace('CEST', '+02:00').replace('CET', '+01:00')` before. – eumiro Jun 06 '12 at 12:28
  • Yep, this is what I'm doing now. I can only hope that the API of Pivotal never decides to do something else or someone decides to change the timezone setting of the Pivotal API User. – Strayer Jun 06 '12 at 13:31