Right versus left timestamps and DST

I was wondering if python makes a distinction between left (right) and right (right) timestamps. This becomes a problem when localizing timestamps on DST days.

Let's say I have the right stamped half hour values ​​in local European time when the DST change occurred from the hour to 02:00 h 03:00 on March 30, 2014.

2014-03-30 00:30:00
2014-03-30 01:00:00
2014-03-30 01:30:00
2014-03-30 02:00:00
2014-03-30 03:30:00
2014-03-30 04:00:00

      

If I want to localize these timestamps, I naturally get the error:

NonExistentTimeError: 2014-03-30 02:00:00

      

since there is no time stamp of 02:00 on this day in this local time zone. So I am wondering if python can make the difference between left / right timestamps?

+3


source to share


2 answers


I think the correct approach is to use UTC when doing any arithmetic and converting from / to UTC with a package pytz

that supports DST changes.



0


source


pytz

allows you to select the utc offset before / after daylight saving time using the parameter is_dst

:



>>> import pytz
>>> tz = pytz.timezone('Europe/Paris')                                                               
>>> from datetime import datetime                                                                    
>>> naive = datetime.strptime('2014-03-30 02:00:00', '%Y-%m-%d %H:%M:%S')                            
>>> tz.localize(naive, is_dst=None)                            
Traceback (most recent call last)
...
NonExistentTimeError: 2014-03-30 02:00:00
>>> tz.localize(naive) #XXX WRONG
datetime.datetime(2014, 3, 30, 2, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
>>> tz.normalize(tz.localize(naive)) # you want this (default is after the transition)
datetime.datetime(2014, 3, 30, 3, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> tz.localize(naive, is_dst=False) #XXX WRONG 
datetime.datetime(2014, 3, 30, 2, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)
>>> tz.localize(naive, is_dst=True) #XXX WRONG 
datetime.datetime(2014, 3, 30, 2, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> tz.normalize(tz.localize(naive, is_dst=False)) # time corresponding to the offset
datetime.datetime(2014, 3, 30, 3, 0, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> tz.normalize(tz.localize(naive, is_dst=True)) # time corresponding to the offset
datetime.datetime(2014, 3, 30, 1, 0, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)

      

0


source







All Articles