Created
March 18, 2016 17:45
-
-
Save jtyberg/2426c3db0ad84433e1d1 to your computer and use it in GitHub Desktop.
Python timezone with DST if pytz unavailable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import timedelta, datetime, tzinfo | |
# Taken from http://stackoverflow.com/questions/6558535/python-find-the-date-for-the-first-monday-after-a-given-a-date | |
def next_weekday(d, weekday): | |
days_ahead = weekday - d.weekday() | |
if days_ahead <= 0: # Target day already happened this week | |
days_ahead += 7 | |
return d + timedelta(days_ahead) | |
class USEastern(tzinfo): | |
def utcoffset(self, dt): | |
return timedelta(hours=-5) + self.dst(dt) | |
def dst(self, dt): | |
# DST starts second Sunday in March | |
d = datetime(dt.year, 3, 1) | |
self.dston = next_weekday(next_weekday(d, 6), 6) | |
# and ends first Sunday in November | |
d = datetime(dt.year, 11, 1) | |
self.dstoff = next_weekday(d, 6) | |
if self.dston <= dt.replace(tzinfo=None) < self.dstoff: | |
return timedelta(hours=+1) | |
else: | |
return timedelta(0) | |
def tzname(self,dt): | |
return "GMT -5" | |
datetime.now(tz=USEastern()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment