Why does creating a datetime with a tzinfo from pytz show a weird time offset?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001
--
Chapters
00:00 Why Does Creating A Datetime With A Tzinfo From Pytz Show A Weird Time Offset?
00:32 Answer 1 Score 1
01:01 Answer 2 Score 3
01:41 Accepted Answer Score 5
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/4575...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime #timezone #pytz
#avk47
ACCEPTED ANSWER
Score 5
There is no problem, datetime just happily reports the offset of the tzinfo in whatever reference frame.
By default pytz.timezone doesn't give the UTC offset but the LMT (local mean time) offset:
>>> pytz.timezone("Europe/Athens")
<DstTzInfo 'Europe/Athens' LMT+1:35:00 STD>
# ^^^-------------------- local mean time
However when you localize it:
>>> var1 = datetime.datetime(2017,10,25,20,10,50)
>>> var1 = pytz.timezone("Europe/Athens").localize(var1)
>>> var1.tzinfo
<DstTzInfo 'Europe/Athens' EEST+3:00:00 DST>
# ^^^^-------------------- eastern european summer time
A different offset is now reported, this time based on the EEST.
ANSWER 2
Score 3
tzinfo doesn't work well for some timezones and that could be the reason for the wrong result.
pytz doc:
Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.
Using localize or astimezone 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.
import datetime, pytz
localTimezone = pytz.timezone('Europe/Athens')
var1 = datetime.datetime(2017,10,25,20,10,50,tzinfo=pytz.utc)
loc_dt = var1.astimezone(localTimezone)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
print(loc_dt.strftime(fmt))
This will print
2017-10-25 23:10:50 EEST+0300
ANSWER 3
Score 1
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.