#!/usr/bin/python3 # needs ~/seepark.ini with # [openweathermap] # apikey=... # cityid=.. # 3319578 for Obsteig, AT from pprint import pprint import requests import configparser import os import datetime baseurl = 'http://api.openweathermap.org/data/2.5/weather' debug = False def getweather(apikey, cityid): query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid) try: response = requests.get(query) if response.status_code != 200: response = 'N/A' return response else: weatherdata = response.json() return weatherdata except requests.exceptions.RequestException as error: print (error) sys.exit(1) def fromtimestamp(timestamp, format): return datetime.datetime.fromtimestamp(timestamp).strftime(format) # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words def degToCompass(num): if num is None: return 'N/A' val=int((num/22.5)+.5) arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"] return arr[(val % 16)] def extractweatherdata(w): data = dict( datetime = w['dt'], sunrise = w['sys']['sunrise'], sunset = w['sys']['sunset'], temp = w['main']['temp'], pressure = w['main']['pressure'], humidity = w['main']['humidity'], visibility = w['visibility'], weather = w['weather'][0]['description'], sky = w['weather'][0]['main'], windspeed = w['wind']['speed'], winddegrees = w['wind']['deg'], cloudiness = w['clouds']['all'], ) data['sunrise_t'] = fromtimestamp(data['sunrise'], '%H:%M:%S') data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S') data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d') data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S') data['winddirection'] = degToCompass(data['winddegrees']) data['precipitation'] = w['rain']['3h'] if 'rain' in w else 'N/A' return data def main(): config = configparser.ConfigParser() config.read(os.path.expanduser('~/seewasser.ini')) apikey = config.get('openweathermap', 'apikey'); cityid = config.get('openweathermap', 'cityid'); weather_raw = getweather(apikey, cityid) if debug: pprint(weather_raw) weather = extractweatherdata(weather_raw) if debug: pprint(weather) # TODO: # write to db # write to csv # output like wetter.at.pl print( weather['date'] + ';' + weather['time'] + ';' + weather['sunrise_t'] + ';' + weather['sunset_t'] + ';' + str(weather['temp']) + ';' + str(weather['precipitation']) + ' mm/h;' + str(weather['windspeed']) + ' km/h ' + weather['winddirection'] + ';' + weather['weather'] + ';' + str(weather['cloudiness']) ) if __name__ == '__main__': main()