Reputation: 8058
I'm trying to convert an UTC
string to a python datetime
object.
The string I want to convert is: 2016-12-16T23:00:00.000Z
and it is in UTC
format. When I convert code to a different timezone I get 2016-12-16 23:00:00+01:00
which is a correct behaviour.
My question is, why when I access the datetime
object, the day is still 16
and not 17
, as I would expect to happen when 1 hour
is added to 23:00
.
What am I missing?
My code
tz = pytz.timezone("Europe/Ljubljana")
dt = datetime.datetime.strptime(start_date, "%Y-%m-%dT%H:%M:%S.000Z")
date = tz.localize(dt)
print 'Date: ', date.strftime('%d')
print 'Date: ', date
Result
Date: 16
Date: 2016-12-16 23:00:00+01:00
Upvotes: 0
Views: 465
Reputation: 9112
This is the expected behavior. dt
has no time zone set. When you call tz.localize(dt)
, you simply assign the timezone.
Here's what you want to do:
tz = pytz.timezone("Europe/Ljubljana")
dt = datetime.datetime.strptime(start_date, "%Y-%m-%dT%H:%M:%S.000Z")
dt = dt.replace(tzinfo=pytz.utc) # you specify the time is UTC
print dt.astimezone(tz) # and now you convert dt to your preferred timezone
You obtain:
datetime.datetime(2016, 12, 17, 0, 0, tzinfo=<DstTzInfo 'Europe/Ljubljana' CET+1:00:00 STD>)
Upvotes: 1