Skip to content

Instantly share code, notes, and snippets.

@buszmen201
Created May 5, 2018 22:07
Show Gist options
  • Save buszmen201/b427fdbf3e3223100fed456d30c8e1c5 to your computer and use it in GitHub Desktop.
Save buszmen201/b427fdbf3e3223100fed456d30c8e1c5 to your computer and use it in GitHub Desktop.
from datetime import datetime
from pytz import timezone
import pytz
from dateutil.tz import *
# GLOBALS #
# left for future
date_format = {
'24': '%d-%m %H:%M %Z',
'12': '%d-%m %I:%M %p %Z'
}
zones = {
'US/Central': timezone('US/Central'),
'US/Eastern': timezone('US/Eastern'),
'US/Pacific': timezone('US/Pacific'),
'US/Mountain': timezone('US/Mountain'),
'GMT': timezone('GMT'),
'BST': timezone('Europe/London'),
'Australia/Sydney': timezone('Australia/Sydney'), # assuning this as AEST
'Pacific/Auckland': timezone('Pacific/Auckland'), # assuming this as NZTZ
}
# END GLOBALS #
class GetTimeZoneName:
timezone = None
country_code = None
def __init__(self, timezone, country_code):
self.country_code = country_code
self.timezone = timezone
def GetTimeZoneName(self):
# see if it's already a valid time zone name
if self.timezone in pytz.all_timezones:
return self.timezone
# if it's a number value, then use the Etc/GMT code
try:
offset = int(self.timezone)
if offset > 0:
offset = '+' + str(offset)
else:
offset = str(offset)
return 'Etc/GMT' + offset
except ValueError:
pass
# look up the abbreviation
country_tzones = None
try:
country_tzones = pytz.country_timezones[self.country_code]
except:
pass
set_zones = set()
if country_tzones is not None and len(country_tzones) > 0:
for name in country_tzones:
tzone = pytz.timezone(name)
for utcoffset, dstoffset, tzabbrev in getattr(tzone, '_transition_info',
[[None, None, datetime.datetime.now(tzone).tzname()]]):
if tzabbrev.upper() == self.timezone.upper():
set_zones.add(name)
if len(set_zones) > 0:
return min(set_zones, key=len)
class Top10TimeZones:
target_date = None
zone = None
def __init__(self, target_date, zone):
self.zone = zone
self.target_date = target_date
def start(self):
parsed_date = datetime.strptime(self.target_date, '%m-%d-%Y %H:%M %p').replace(tzinfo=gettz(self.zone))\
.astimezone(pytz.utc)
print()
print(f"UTC{'':17} {parsed_date.strftime(date_format['24'])}")
for zonename, zone in zones.items():
date = parsed_date.astimezone(zone)
print(f"{zonename:<20} {date.strftime(date_format['12'])}")
#
# MAIN APP
#
while True:
try:
target = input("Provide datetime in MM-DD-YYYY HH:MM AM/PM format: ")
datetime.strptime(target, '%m-%d-%Y %H:%M %p')
break
except:
pass
get_zone = None
while get_zone is None:
abbr = input("Provide time zone name, like UTC, AEDT: ")
country = input('Provide two Letter Coutry Code, like UK, US, CZ: ')
get_zone = GetTimeZoneName(abbr, country).GetTimeZoneName()
Top10TimeZones(target, get_zone).start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment