2

How do you unserialize a timezone-aware datetime object? PYYAML will automatically save them correctly in the ISO format, but drops the timezone info when loading. Using str(my_datetime_object) makes a correct ISO string, but the datetime module has no clean way to convert it back to a datetime object. (strftime has no ISO-compatible timezone format)

dateutil.parser.parse does something weird that's still not right:

In [113]: x
Out[113]: datetime.datetime(2014, 2, 15, 21, 58, 25, 866385, tzinfo=<DstTzInfo 'Europe/Athens' EET+2:00:00 STD>)

In [114]: str(x)
Out[114]: '2014-02-15 21:58:25.866385+02:00'

In [115]: dateutil.parser.parse(str(x))
Out[115]: datetime.datetime(2014, 2, 15, 21, 58, 25, 866385, tzinfo=tzoffset(None, 7200))
Turtles Are Cute
  • 3,200
  • 6
  • 30
  • 38
  • 2
    It is a correct result. `7200 = 2 * 60 * 60 = hour_offset * 60*minutes/hour * 60*seconds/minute`. It can not know that you are in Athen since this is a string and the information is lost when it is not shown in the string. You will need an format that also allows the town. – User Feb 16 '14 at 08:04
  • What do you mean by "unserialize a timezone-aware datetime object"? Do you want to transform it into a known timezone or just output it as string? – chris.tian Feb 16 '14 at 08:20
  • 1
    possible duplicate of [How do I translate a ISO 8601 datetime string into a Python datetime object?](http://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object) – Jacinda Feb 16 '14 at 08:34
  • 1
    Take a look at this question. Many of the answers talk about handling timezone-aware objects: http://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object – Jacinda Feb 16 '14 at 08:35
  • User - that checks. If you write it as an answer, I'll mark it as correct. – Turtles Are Cute Feb 22 '14 at 07:03

1 Answers1

1

You should serialize this to a datetime and a timezone. The timezone should be stored as the Timezone name, in this case 'Europe/Athens'. What format you use for the datetime is less important, but I'd recommend serializing the datetime as a separate field from the timezone, and using UTC, and explicitly so. How this looks more explicitly is entirely dependent on how the rest of your seialization format looks.

For example:

{datetime: "2014-02-15 19:58:25.866385+00:00", timezone: "Europe/Athens"}
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
  • to get the timezone id, `x.tzinfo.zone` could be used with pytz timezones (such as in this case). If datetime is serialized as UTC time then `utc_aware.astimezone(tz)` could be called, to get an aware datetime object in `tz` timezone. – jfs May 12 '15 at 16:55