Changing the time zone in Python

I probably missed something about time zones:

>>> import datetime, pytz >>> date = datetime.datetime(2013,9,3,16,0, tzinfo=pytz.timezone("Europe/Paris")) >>> date.astimezone(pytz.UTC) datetime.datetime(2013, 9, 3, 15, 51, tzinfo=<UTC>) 

I expected

 datetime.datetime(2013, 9, 3, 15, 00, tzinfo=<UTC>) 

Can someone explain to me where these 51 minutes come from?

Thanks,

Jean philip

+6
source share
3 answers

The UTC offset gives ( date.tzinfo.utcoffset(date) ):

 datetime.timedelta(0, 540) 

It is 540 seconds or 9 minutes.

In France, the switch to UTC was made on March 11, 1911, and the clock was returned for 9 minutes and 21 seconds ( source 1 , source 2 ):

Until 1911, Paris had 9 minutes and 21 seconds with UTC.

You can also see it here ( time in Paris in 1911), where time runs from March 11, 12:01:00 to March 10, 11:51:39 PM.

+6
source

Read the note at the very beginning of the pytz documentation ; use the .localize() method to create a datetime object that supports the time zone:

 import datetime import pytz naive_dt = datetime.datetime(2013,9,3,16,0) dt = pytz.timezone("Europe/Paris").localize(naive_dt, is_dst=None) to_s = lambda d: d.strftime('%Y-%m-%d %H:%M:%S %Z%z') print(to_s(dt)) print(to_s(dt.astimezone(pytz.utc))) 

Output

 2013-09-03 16:00:00 CEST+0200 2013-09-03 14:00:00 UTC+0000 

I do not know why you expect 15:00 UTC here.

+4
source

Thanks to Simeon for your reply. It made me realize how shallow my understanding of all this is. The following experiments lost me a little more ...

 >>> import datetime, pytz >>> date_paris = datetime.datetime(2013,9,3,16,0, tzinfo=pytz.timezone("Europe/Paris")) >>> date_utc = datetime.datetime(2013,9,3,16,0, tzinfo=pytz.utc) >>> date_paris.astimezone(pytz.utc) datetime.datetime(2013, 9, 3, 15, 51, tzinfo=<UTC>) >>> date_utc.astimezone(pytz.timezone("Europe/Paris")) datetime.datetime(2013, 9, 3, 18, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>) 

Why does this 9-minute shift appear when converting in one direction, but not in the other? The following piece of code concentrates all the frustration:

 >>> date_paris datetime.datetime(2013, 9, 3, 16, 0, tzinfo=<DstTzInfo 'Europe/Paris' PMT+0:09:00 STD>) >>> date_paris.astimezone(pytz.utc).astimezone(pytz.timezone("Europe/Paris")) datetime.datetime(2013, 9, 3, 17, 51, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>) 
0
source

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


All Articles