简体   繁体   中英

Unserialize Python aware datetime

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))

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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM