Last active
January 3, 2016 10:49
-
-
Save fredrikbonander/8452496 to your computer and use it in GitHub Desktop.
Simple TZ implementation
This file contains 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 datetime, tzinfo, timedelta | |
class TZOffset(tzinfo): | |
def __init__(self, offset=0, *args, **kwds): | |
self.gmt_offset = offset | |
super(TZOffset, self).__init__(*args, **kwds) | |
def utcoffset(self, dt): | |
return timedelta(hours=self.gmt_offset) + self.dst(dt) | |
def tzname(self,dt): | |
return "GMT %s%s" % (('+' if self.gmt_offset > 0 else ''), self.gmt_offset) | |
def dst(self,dt): | |
d = datetime(dt.year, 4, 1) | |
self.dston = d - timedelta(days=d.weekday() + 1) | |
d = datetime(dt.year, 11, 1) | |
self.dstoff = d - timedelta(days=d.weekday() + 1) | |
if self.dston <= dt.replace(tzinfo=None) < self.dstoff: | |
return timedelta(hours=1) | |
else: | |
return timedelta(0) | |
def as_time_zone(dt, tz): | |
if dt.tzinfo is None: | |
dt = dt.replace(tzinfo=TZOffset(0)) | |
if dt.tzinfo is tz: | |
return dt | |
utc = (dt - dt.utcoffset()).replace(tzinfo=tz) | |
return tz.fromutc(utc) | |
now = datetime.now() | |
now_gmt_1 = datetime.now(TZOffset(1)) | |
tz_1 = TZOffset(0) | |
tz_2 = TZOffset(-12) | |
tz_3 = TZOffset(2) | |
now_tz_aware = now.replace(tzinfo=tz_1) | |
now_with_new_tz = as_time_zone(now_tz_aware, tz_2) | |
now_with_new_tz_2 = as_time_zone(now_with_new_tz, tz_3) | |
dt1 = datetime(2014, 12, 24, 16, 30, tzinfo=tz_1) | |
dt2 = dt1.replace(month=06) | |
print 'Date \t \t \t \t \t', 'Timezone' | |
print now, ' \t \t', now.tzname() | |
print now_gmt_1, '\t', now_gmt_1.tzname() | |
print now_with_new_tz, '\t', now_with_new_tz.tzname() | |
print now_with_new_tz_2, '\t', now_with_new_tz_2.tzname() | |
print 'Daylight Savings' | |
print 'Wintertime', dt1.utctimetuple() | |
print 'Summertime', dt2.utctimetuple() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment