strompreis/collectors/weather.py

36 lines
1.1 KiB
Python

from datetime import datetime, timedelta, timezone
from utils import request_utils
import polars as pl
def fetch_weather(lat: float = 52.52, lon: float = 13.41) -> pl.DataFrame:
url = "https://api.brightsky.dev/weather"
headers = {"Accept": "application/json"}
current_utc = datetime.now(timezone.utc)
payload = {
"date": (current_utc - timedelta(hours=72)).isoformat(),
"last_date": current_utc.isoformat(),
"lat": lat,
"lon": lon,
"units": "dwd",
"tz": "Etc/UTC",
}
data = request_utils.make_requests(url, headers, payload, 20)
relevant_fields = [
"temperature",
"wind_speed",
"solar",
"sunshine",
"cloud_cover",
"precipitation",
]
critical_fields = ["temperature", "wind_speed"]
weather_data = [
{k: v for k, v in entry.items() if k in relevant_fields or k in ["timestamp"]}
for entry in data["weather"]
if all(entry.get(field) is not None for field in critical_fields)
]
df_weather = pl.DataFrame(weather_data)
return df_weather