Friday, 11 May 2018

datetime - Using python to determine if a timestamp is under daylight savings time



This does not work:



t = os.path.getmtime(filename)

dTime = datetime.datetime.fromtimestamp(t)
justTime = dTime.timetuple()
if justTime.tm_isdst == 0 :
tDelta = datetime.timedelta(hours=0)
else:
tDelta = datetime.timedelta(hours=1)


What happens instead is that the conditional always equals 1, despite some of the timestamps being within daytime savings time.




I am trying to make a python call match the behavior of a c-based call.


Answer



To find out whether a given timestamp corresponds to daylight saving time (DST) in the local time zone:



import os
import time

timestamp = os.path.getmtime(filename)
isdst = time.localtime(timestamp).tm_isdst > 0



It may fail. To workaround the issues, you could get a portable access to the tz database using pytz module:



from datetime import datetime
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # get pytz tzinfo
isdst = bool(datetime.fromtimestamp(timestamp, local_timezone).dst())



Related: Use Python to find out if a timezone currently in daylight savings time.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...