Last active
August 4, 2022 13:16
-
-
Save zed/4136246 to your computer and use it in GitHub Desktop.
find local timezones as pytz.timezone objects
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
#!/usr/bin/env python | |
import os | |
import time | |
from datetime import timedelta | |
from hashlib import sha512 | |
import pytz # pip install pytz | |
def filehash(path): | |
with open(path, 'rb') as file: | |
return sha512(file.read()).hexdigest() | |
def local_timezones_from_etc_localtime(): | |
""" | |
http://stackoverflow.com/a/7841417 | |
""" | |
tzfile_digest = filehash('/etc/localtime') | |
topdir = "/usr/share/zoneinfo/" | |
for pathdir, dirs, files in os.walk(topdir): | |
for filename in files: | |
path = os.path.join(pathdir, filename) | |
if filehash(path) == tzfile_digest: | |
tzname = path[len(topdir):] | |
try: | |
yield pytz.timezone(tzname) | |
except pytz.UnknownTimeZoneError: | |
pass | |
def local_timezones_from_current_tzname_offset(): | |
""" | |
http://stackoverflow.com/a/8328904 | |
""" | |
if time.daylight and time.localtime().tm_isdst > 0: | |
local_time_offset = time.altzone | |
localtzname = time.tzname[1] | |
else: | |
local_time_offset = time.timezone | |
localtzname = time.tzname[0] | |
local_offset = timedelta(seconds=-local_time_offset) | |
for name in pytz.all_timezones: | |
timezone = pytz.timezone(name) | |
if not hasattr(timezone, '_tzinfos'): | |
continue #skip, if some timezone doesn't have info | |
# go thru tzinfo and see if short name like EDT and offset matches | |
for (utcoffset, daylight, tzname), _ in timezone._tzinfos.items(): | |
if utcoffset == local_offset and tzname == localtzname: | |
yield timezone | |
if __name__ == '__main__': | |
print({tz.zone: tz for tz in local_timezones_from_etc_localtime()}) | |
print({tz.zone: tz for tz in local_timezones_from_current_tzname_offset()}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment