Skip to content

Instantly share code, notes, and snippets.

@gvanrossum gvanrossum/tzl.py
Last active May 29, 2019

Embed
What would you like to do?
local timezone class
# A local timezone class that inherits its behavior from the time
# module's knowledge about the local time zone.
# TODO: Use tm_gmtoff and tm_zone if supported? (Probably should be a
# separate class so we can compare them.)
import calendar # TODO: Really shouldn't.
import datetime
import time
class LocalTimeZone(datetime.tzinfo):
"""Local timezone class that defers to the time module."""
# TODO: Inline _mktime() and _localtime().
def _mktime(self, dt):
assert dt.tzinfo is self
return time.mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
-1, -1, -1))
def _localtime(self, dt):
return time.localtime(self._mktime(dt))
def _isdst(self, dt):
return time.daylight and self._localtime(dt).tm_isdst > 0
def _zoff(self, dt):
return time.altzone if self._isdst(dt) else time.timezone
def tzname(self, dt):
if dt is None:
return None
dst = self._isdst(dt)
return time.tzname[dst]
def utcoffset(self, dt):
if dt is None:
return None
zoff = self._zoff(dt)
return datetime.timedelta(seconds=zoff)
def dst(self, dt):
if dt is None:
return None
zoff = self._zoff(dt)
return datetime.timedelta(seconds=(time.timezone - zoff))
# Inherit fromutc() from the base class.
class BetterLocalTimeZone(LocalTimeZone):
def tzname(self, dt):
if dt is None:
return None
tt = self._localtime(dt)
return tt.tm_zone
def _zoff(self, dt):
tt = self._localtime(dt)
return tt.tm_gmtoff
if not time.daylight:
local_tz = datetime.timezone(time.timezone, time.tzname[0])
elif hasattr(time.localtime(), 'tm_zone') and hasattr(time.localtime(), 'tm_gmtoff'):
local_tz = BetterLocalTimeZone()
else:
local_tz = LocalTimeZone()
print(local_tz.__class__.__name__)
dt = datetime.datetime.now(tz=local_tz)
print(dt.strftime("%a %b %d %H:%M:%S %Y %Z (%z)"))
dt += datetime.timedelta(180)
print(dt.strftime("%a %b %d %H:%M:%S %Y %Z (%z)"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.