2019-03-13 23:28:05 +01:00
|
|
|
import sys
|
2019-03-13 23:02:54 +01:00
|
|
|
import argparse
|
|
|
|
|
|
|
|
import dateparser
|
|
|
|
from pytz.exceptions import UnknownTimeZoneError
|
|
|
|
|
|
|
|
|
|
|
|
parser = argparse.ArgumentParser()
|
2019-03-13 23:21:33 +01:00
|
|
|
parser.add_argument('human_dt', help="datetime-like string")
|
|
|
|
parser.add_argument('human_tz', nargs='?', help="timezone-like or location string")
|
|
|
|
parser.add_argument('--format', dest='format', default='%Y-%m-%d %H:%M:%S%z')
|
2019-03-13 23:02:54 +01:00
|
|
|
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
|
2019-03-13 23:28:05 +01:00
|
|
|
from geopy.exc import GeocoderTimedOut
|
2019-03-13 23:02:54 +01:00
|
|
|
from timezonefinder import TimezoneFinder
|
|
|
|
|
|
|
|
user_agent = ''.join(random.choices(string.ascii_uppercase + string.digits, k=20))
|
|
|
|
geolocator = Nominatim(user_agent=user_agent)
|
2019-03-13 23:28:05 +01:00
|
|
|
try:
|
|
|
|
location = geolocator.geocode(human_tz)
|
|
|
|
except GeocoderTimedOut:
|
|
|
|
print("Timed out resolving location. Try specifying a timezone directly", file=sys.stderr)
|
|
|
|
exit(1)
|
|
|
|
|
2019-03-13 23:02:54 +01:00
|
|
|
|
|
|
|
tzf = TimezoneFinder()
|
|
|
|
loc_tz = tzf.timezone_at(lng=location.longitude, lat=location.latitude)
|
|
|
|
result = dateparser.parse(human_dt, settings={'TO_TIMEZONE': loc_tz})
|
|
|
|
|
2019-03-13 23:21:33 +01:00
|
|
|
if result is None:
|
2019-03-13 23:28:05 +01:00
|
|
|
print("Could not parse '{human_dt}' or '{human_tz}'".format(human_dt, human_tz), file=sys.stderr)
|
2019-03-13 23:21:33 +01:00
|
|
|
exit(1)
|
|
|
|
|
|
|
|
formatted_result = result.strftime(args.format)
|
|
|
|
print(formatted_result)
|