Datetime: conversion from string with timezone name does not work

I have the following line, "2017-03-30 08:25:00CET" , which I want to convert to a dtetime tz-aware object.

According to this SO question , from python 3.2 this can be done using only the datetime module. Also, from the documentation , I see

 %z | UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). | (empty), +0000, -0400, +1030 %Z | Time zone name (empty string if the object is naive). | (empty), UTC, EST, CST 

So, I will try the following

 datetime.strptime(dep_dt, '%Y-%m-%d %H:%M:%S%Z') 

I don't get any errors, but then the object I get is not tz-aware

 datetime.datetime(2017, 3, 30, 8, 25) 

On the other hand, if I convert my string to "2017-03-30 08:25:00+0200" and then convert it to an object with

datetime.strptime(dep_dt, '%Y-%m-%d %H:%M:%S%z')

I get tat-aware datetime:

 datetime.datetime(2017, 3, 30, 8, 25, tzinfo=datetime.timezone(datetime.timedelta(0, 7200))) 

Any ideas on why it works with %z but not with %z ? What am I doing wrong?

+8
python timezone python-datetime
source share
1 answer

Judging by the information provided by tzinfo , %Z does not work the way you feed the string, for example, "UTC" , and it will return a datetime instance with the correct time zone.

pytz provides a possible solution to your problem. However, the documentation says that there is no guarantee that your time zone will be recognized by datetime and recommends working with UTC for as long as possible.

Solution using pytz :

 from datetime import datetime from pytz import timezone dep_dt = '2017-03-30 08:25:00CET' dt = datetime.strptime(dep_dt, '%Y-%m-%d %H:%M:%S%Z') timezone(dep_dt[19:]).localize(dt) 

Of:

 datetime.datetime(2017, 3, 30, 8, 25, tzinfo=<DstTzInfo 'CET' CEST+2:00:00 DST>) 
+4
source share

All Articles