Why does creating a datetime with tzinfo from pytz show a weird time offset?

Can someone explain to me why I am not getting the same result?

import datetime,pytz var1 = datetime.datetime(2017,10,25,20,10,50,tzinfo=pytz.timezone("Europe/Athens"))) print(var1) 

The output of this code: 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: 2017-10-25 20:10:50+03:00

My question is why they have different time zones (1:35 and 3:00). I know that the second code is correct, because my UTC is 3:00 . But can you tell me why I get 1:35 in the first?

+5
source share
3 answers

There are no problems, datetime only joyfully reports the tzinfo offset in any reference frame.

By default, pytz.timezone does not give a UTC offset, but LMT (local average 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 

Another offset is now reported, this time based on EEST.

+1
source

In the second code, you use .localize() , which takes a naive datetime object and interprets it as if it were in this time zone. It does not move time to another time zone. The naive datetime object does not have time zone information to be able to make this possible.

How are you By making the time local in the second code, the time indicated in the second is correct. Since you are not having the time local in the first code, the time shown is incorrect.

+1
source

tzinfo does not work well for some time zones, and this may be causing the wrong result.
pytz doc :

Unfortunately, using the tzinfo argument of standard datetime 'constructors does not work with pytz for many time zones.

Using localize or astimezone is the solution to this problem. Doc says the preferred way to deal with time is to always work in UTC, converting it to local time only when generating output for reading by people.

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

Will open

 2017-10-25 23:10:50 EEST+0300 
+1
source

Source: https://habr.com/ru/post/1270991/


All Articles