Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly parse date string with timezone information

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

like image 649
Strayer Avatar asked Jun 06 '12 12:06

Strayer


People also ask

How do you parse time from a date?

The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.

What is T and Z in timestamp?

The T is just a literal to separate the date from the time, and the Z means “zero hour offset” also known as “Zulu time” (UTC).


1 Answers

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>)
like image 171
eumiro Avatar answered Sep 28 '22 11:09

eumiro