From 93a30d5cd96e41af68c7046099b764e1cd3c6487 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Fri, 17 Jul 2020 19:31:38 +0200 Subject: [PATCH] Update weather module --- modules/weather.py | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/modules/weather.py b/modules/weather.py index c02cfc5..03e835b 100644 --- a/modules/weather.py +++ b/modules/weather.py @@ -1,3 +1,5 @@ +from datetime import datetime + import requests # Translation: https://erikflowers.github.io/weather-icons/api-list.html @@ -60,11 +62,44 @@ ICONS = { } +def format_temp(temp): + return str(round(temp)) + + +def get_day(ts): + return datetime.utcfromtimestamp(ts).strftime("%a") + + +def get_icon(id, dt=1, sunrise=1, sunset=1): + time = "" + if sunrise <= dt <= sunset: + time = "day" + else: + time = "night" + return ICONS[id][time] + + def get_weather(token, lat, lon): + current, daily = [], [] r = requests.get( "https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&appid={}&eclude=minutely,hourly&units=metric".format( lat, lon, token ) ) - data = r.json() - return ICONS[data["current"]["weather"][0]["id"]]["day"] + data_current = r.json()["current"] + data_daily = r.json()["daily"] + + dt = data_current["dt"] + sr = data_current["sunrise"] + ss = data_current["sunset"] + current.append(get_icon(data_current["current"]["weather"][0]["id"], dt, sr, ss)) + current.append(format_temp(data_current["temp"])) + + for i in range(1, 4): + day = get_day(data_daily[i]["dt"]) + min = format_temp(data_daily[i]["temp"]["min"]) + max = format_temp(data_daily[i]["temp"]["max"]) + icon = get_icon(data_daily[i]["weather"][0]["id"]) + daily.append([day, min, max, icon]) + + return current, daily -- 2.44.0