JSON and Scraping
#
# Compute how long until Christmas in any timezone.
# Uses JSON from an online API: http://worldtimeapi.org/
#
# Input examples:
# local
# America/Phoenix
# Europe/Vienna
#
import requests
from datetime import datetime
tz = input('What timezone ("local" also an option)? ')
if tz.lower() == 'local':
tz = "America/New_York"
# Make the JSON query
data = requests.get("http://worldtimeapi.org/api/timezone/" + tz)
json = data.json()
# Create the NOW datetime object.
dt = datetime.strptime(json['datetime'], '%Y-%m-%dT%H:%M:%S.%f%z')
print('Current time is', dt)
# Create a proper 12/25 datetime with timezone and current year.
xmas_str = str(dt.year) + '-12-25' + json['utc_offset']
christmas = datetime.strptime(xmas_str, '%Y-%m-%d%z')
# Compute and print the time difference.
diff = christmas-dt
print('Christmas is', diff.days, 'days', diff.seconds//3600, 'hours and',
diff.seconds//60%60, 'minutes away.')