#!/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.get('dt'), sunrise = w.get('sys').get('sunrise'), sunset = w.get('sys').get('sunset'), temp = w.get('main').get('temp'), pressure = w.get('main').get('pressure'), humidity = w.get('main').get('humidity'), visibility = w.get('visibility'), weather=w['weather'][0]['description'], sky=w['weather'][0]['main'], windspeed=w.get('wind').get('speed'), winddegrees=w.get('wind').get('deg'), cloudiness=w.get('clouds').get('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']) 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']) + ';' + ';' + # precipitation missing? or only in XML: https://openweathermap.org/current ? str(weather['windspeed']) + 'km/h ' + weather['winddirection'] + ';' + weather['weather'] + ';' + str(weather['cloudiness']) ) if __name__ == '__main__': main()