Skip to content

Instantly share code, notes, and snippets.

@beugley
Created January 16, 2020 13:08
Show Gist options
  • Save beugley/1c5b8c13331373ce25bde88903c8e199 to your computer and use it in GitHub Desktop.
Save beugley/1c5b8c13331373ce25bde88903c8e199 to your computer and use it in GitHub Desktop.
Python class to determine if a datetime string occurred during STD or DST
#!/usr/bin/env python3
import datetime as dt
import subprocess
class STD_DST(dt.tzinfo):
""" Determine if a datetime occured during STD or DST time """
def dst(self, a):
# DST starts second Sunday in March at 2AM
d = dt.datetime(a.year, 3, 1, 2)
self.dston = d + dt.timedelta(days=14-(d.weekday()+1))
# DST ends first Sunday in November at 2AM
d = dt.datetime(a.year, 11, 1, 2)
self.dstoff = d + dt.timedelta(days=7-(d.weekday()+1))
if self.dston <= a.replace(tzinfo=None) < self.dstoff:
return dt.timedelta(hours=1)
else:
return dt.timedelta(0)
def tzname(self,a):
if self.dst(a):
return("DST")
else:
return("STD")
def utcoffset(self, a):
# Use any date that's in STD time to get the standard offset from UTC.
# That's 5 hours for EST.
cmd = subprocess.run(["date", "-d@1451624400", "+%:z"],
stdout=subprocess.PIPE)
std_offset = int(cmd.stdout.decode().split(':')[0][1:])
# Return the time difference between a and UTC.
return dt.timedelta(hours=std_offset) - self.dst(a)
if __name__ == "__main__":
std_dst = STD_DST()
assert(dt.datetime(2016,3,13,1,59,0,tzinfo=std_dst).tzname() == 'STD')
assert(dt.datetime(2016,3,13,2,0,0,tzinfo=std_dst).tzname() == 'DST')
assert(dt.datetime(2016,11,6,1,59,0,tzinfo=std_dst).tzname() == 'DST')
assert(dt.datetime(2016,11,6,2,0,0,tzinfo=std_dst).tzname() == 'STD')
assert(dt.datetime(2016,3,13,1,59,0,tzinfo=std_dst).utcoffset()
== dt.timedelta(hours=5))
assert(dt.datetime(2016,3,13,2,0,0,tzinfo=std_dst).utcoffset()
== dt.timedelta(hours=4))
assert(dt.datetime(2016,11,6,1,59,0,tzinfo=std_dst).utcoffset()
== dt.timedelta(hours=4))
assert(dt.datetime(2016,11,6,2,0,0,tzinfo=std_dst).utcoffset()
== dt.timedelta(hours=5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment