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