#!/usr/bin/env python3 """Current weather from wttr.in as compact JSON: {ok, place, celsius, feelsCelsius, code, description, humidity, wind, hourly}.""" import datetime, json, sys, urllib.parse, urllib.request def upcoming(data, now, count=4): """The next `count` three-hourly forecasts: [{hour, celsius, code}]. wttr.in usually omits the local observation time, so this machine's clock stands in.""" try: observed = datetime.datetime.strptime(now['localObsDateTime'], '%Y-%m-%d %I:%M %p') except (KeyError, ValueError): observed = datetime.datetime.now() slots = [] for day in data.get('weather') or []: for slot in day.get('hourly') or []: try: at = datetime.datetime.strptime(day['date'], '%Y-%m-%d') + datetime.timedelta(hours=int(slot['time']) // 100) if at > observed: slots.append(dict(hour=at.hour, celsius=float(slot['tempC']), code=int(slot['weatherCode']))) except (KeyError, ValueError): continue return slots[:count] def main(): location = sys.argv[1] if len(sys.argv) > 1 else '' url = 'https://wttr.in/' + urllib.parse.quote(location) + '?format=j1' try: with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'glassMxrph'}), timeout=12) as response: data = json.load(response) now = data['current_condition'][0] area = (data.get('nearest_area') or [{}])[0] place = (area.get('areaName') or [{'value': ''}])[0]['value'] print(json.dumps(dict(ok=True, place=place or location, celsius=float(now['temp_C']), feelsCelsius=float(now['FeelsLikeC']), code=int(now['weatherCode']), description=now['weatherDesc'][0]['value'].strip(), humidity=int(now['humidity']), wind=float(now['windspeedKmph']), hourly=upcoming(data, now)))) except Exception as error: # Network, HTTP and format errors all surface as a message. print(json.dumps(dict(ok=False, error=str(error)))) if __name__ == '__main__': main()