tww/tz.py

38 lines
1.1 KiB
Python
Raw Normal View History

2019-03-13 23:02:54 +01:00
import argparse
import dateparser
from pytz.exceptions import UnknownTimeZoneError
parser = argparse.ArgumentParser()
parser.add_argument('human_dt')
parser.add_argument('human_tz', nargs='?')
args = parser.parse_args()
human_dt = args.human_dt
human_tz = args.human_tz
try:
# first try parsing the timezone from user input
if human_tz:
result = dateparser.parse(human_dt, settings={'TO_TIMEZONE': human_tz})
else:
result = dateparser.parse(human_dt)
except UnknownTimeZoneError:
# we don't know this timezone one, assume location
import random
import string
from geopy.geocoders import Nominatim
from timezonefinder import TimezoneFinder
user_agent = ''.join(random.choices(string.ascii_uppercase + string.digits, k=20))
geolocator = Nominatim(user_agent=user_agent)
location = geolocator.geocode(human_tz)
tzf = TimezoneFinder()
loc_tz = tzf.timezone_at(lng=location.longitude, lat=location.latitude)
result = dateparser.parse(human_dt, settings={'TO_TIMEZONE': loc_tz})
print(result)