3 # needs ~/seepark.ini with
7 # 3319578 for Obsteig, AT
9 from pprint import pprint
19 baseurl = 'http://api.openweathermap.org/data/2.5/weather'
22 def getweather(apikey, cityid):
23 query = baseurl + '?units=metric&APPID={}&id={}&lang=de'.format(apikey, cityid)
25 response = requests.get(query)
26 if response.status_code != 200:
30 weatherdata = response.json()
32 except requests.exceptions.RequestException as error:
37 def fromtimestamp(timestamp, format):
38 return datetime.datetime.fromtimestamp(timestamp).strftime(format)
41 # https://stackoverflow.com/questions/7490660/converting-wind-direction-in-angles-to-text-words
42 def degToCompass(num):
43 if num is None or num is math.nan:
45 val=int((num/22.5)+.5)
46 arr=["N","NNO","NO","ONO","O","OSO", "SO", "SSO","S","SSW","SW","WSW","W","WNW","NW","NNW"]
47 return arr[(val % 16)]
50 def extractweatherdata(w):
51 w['wind']['deg'] = math.nan
54 sunrise = w['sys']['sunrise'],
55 sunset = w['sys']['sunset'],
56 temp = w['main']['temp'],
57 pressure = w['main']['pressure'],
58 humidity = w['main']['humidity'],
59 visibility = w['visibility'],
60 weather = w['weather'][0]['description'],
61 sky = w['weather'][0]['main'],
62 windspeed = w['wind']['speed'],
63 cloudiness = w['clouds']['all'],
66 data['sunrise_t'] = fromtimestamp(data['sunrise'], '%H:%M:%S')
67 data['sunset_t'] = fromtimestamp(data['sunset'], '%H:%M:%S')
68 data['date'] = fromtimestamp(data['datetime'], '%Y-%m-%d')
69 data['time'] = fromtimestamp(data['datetime'], '%H:%M:%S')
70 data['winddegrees'] = w['wind']['deg'] if 'deg' in w['wind'] else math.nan
71 data['winddirection'] = degToCompass(data['winddegrees'])
72 data['precipitation'] = w['rain']['3h'] if 'rain' in w else math.nan
77 def write_csv(csv_file, weather_data):
78 """output like wetter.at.pl"""
79 with open(csv_file, "a", newline="") as file:
80 writer = csv.writer(file, dialect="excel", delimiter=';')
84 weather_data['sunrise_t'],
85 weather_data['sunset_t'],
86 "{:.2f}".format(weather_data['temp']),
87 "{:.2f} mm/h".format(weather_data['precipitation']),
88 "{:.1f} km/h {}".format(weather_data['windspeed'], weather_data['winddirection']),
89 weather_data['weather'],
90 "{}".format(weather_data['cloudiness'])
95 config = configparser.ConfigParser()
96 config.read(configfile)
97 apikey = config.get('openweathermap', 'apikey')
98 cityid = config.get('openweathermap', 'cityid')
99 csvfile = config.get("openweathermap", 'csvfilename')
101 weather_raw = getweather(apikey, cityid)
104 weather = extractweatherdata(weather_raw)
112 write_csv(os.path.expanduser(csvfile), weather)
115 if __name__ == '__main__':
116 default_config_file = os.path.expanduser('~/seewasser.ini')
117 parser = argparse.ArgumentParser(description='Get OpenWeathermap data')
118 parser.add_argument('--config', default=default_config_file, help='configuration file')
119 args = parser.parse_args()