Can someone explain me why I do not get the same result in those?
import datetime,pytz
var1 = datetime.datetime(2017,10,25,20,10,50,tzinfo=pytz.timezone("Europe/Athens")))
print(var1)
The output of this code is: 2017-10-25 20:10:50+01:35
import datetime,pytz
var1 = datetime.datetime(2017,10,25,20,10,50)
var1 = pytz.timezone("Europe/Athens").localize(var1)
print(var1)
The output of this code is: 2017-10-25 20:10:50+03:00
My question is why they have different timezones (1:35 and 3:00). I know that the second code is true because my UTC is 3:00
. But can you tell me why I am getting 1:35
in the first one?
There is no problem,
datetime
just happily reports the offset of thetzinfo
in whatever reference frame.By default
pytz.timezone
doesn't give the UTC offset but the LMT (local mean time) offset:However when you localize it:
A different offset is now reported, this time based on the EEST.
tzinfo
doesn't work well for some timezones and that could be the reason for the wrong result.pytz doc:
Using
localize
orastimezone
is a fix to this problem. Doc says that The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.This will print
In the second code, you use
.localize()
, which takes a naive datetime object and interprets it as if it is in that timezone. It does not move the time to another timezone. A naive datetime object has no timezone information to be able to make that move possible.As you are making the time local in the second code, the time shown in the second one is correct. As you are not making the time local in the first code, the time shown is incorrect.