You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.7 KiB
Python

5 years ago
import datetime
import os.path
import requests
def get_weather_json(lat, lon):
"""
fetches weather from the Norwegian meteorological institute
for a given latitude and longitude. Returns an object with a
3-day forecast with morning, afternoon, evening and overnight
periods. NOTE: This is not tidied up. Use get_forecast for
nicer formatted stuff.
"""
url = "https://api.met.no/weatherapi/locationforecast/1.9/.json"
params = { "lat": lat, "lon": lon }
# https://api.met.no/weatherapi/locationforecast/1.9/.json?lat=52.50639&lon=13.4063
resp = requests.get(url=url, params=params)
return resp.json()
def get_forecast(lat, lon):
"""
returns a list of forecast dicts:
forecast = { "fromtime": datetime, "totime": datetime,
"symbol": "pathto.svg", "mintemp": "12.7",
"maxtemp": "16.8", "period": "Morning"}
"""
thisdir = os.path.dirname(os.path.abspath(__file__))
periods = {6: "Morning", 12: "Afternoon", 18: "Evening", 0: "Night"}
# Berlin - "52.5", "13.4"
w = get_weather_json(lat, lon)
forecasts = []
for t in w["product"]["time"]:
# need to strip the trainling 'Z' char which indicates UTC
fr = datetime.datetime.fromisoformat(t["from"][:-1])
to = datetime.datetime.fromisoformat(t["to"][:-1])
dtdelta = datetime.date.today() - fr.date()
if dtdelta == datetime.timedelta(days=0):
day_of = "Today"
elif dtdelta == datetime.timedelta(days=-1):
day_of = "Tomorrow"
else:
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
day_of = days[fr.weekday()]
if fr.hour not in (0, 6, 12, 18):
continue
if(to-fr == datetime.timedelta(hours=6)):
mintemp = t["location"]["minTemperature"]["value"]
maxtemp = t["location"]["maxTemperature"]["value"]
symbol = t["location"]["symbol"]["id"].lower()
png = symbol
if fr.hour in (18, 0):
symbol += "-night.svg"
png += "-night.png"
else:
symbol += ".svg"
png += ".png"
icon = os.path.join(thisdir, "weather_icons", symbol)
png = os.path.join(thisdir, "weather_icons", png)
5 years ago
forecast = {"fromtime": fr, "totime": to, "symbol": icon,
"mintemp": mintemp, "maxtemp": maxtemp, "png": png,
"period": periods[fr.hour], "day": day_of}
forecasts.append(forecast)
return forecasts
if __name__ == "__main__":
from pprint import pprint
pprint(get_forecast("52.5","13.4"))