Skip to content

Commit

Permalink
Issue/fix open meteo (#228)
Browse files Browse the repository at this point in the history
* change to use openmeteo_requests

* format
  • Loading branch information
peterdudfield authored Dec 2, 2024
1 parent ffbaad7 commit 0c57760
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions quartz_solar_forecast/weather/open_meteo.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from datetime import datetime
from typing import List

import openmeteo_requests
import pandas as pd
import requests
import requests_cache
from retry_requests import retry


class WeatherService:
Expand Down Expand Up @@ -91,9 +94,7 @@ def _validate_date_format(self, start_date: str, end_date: str) -> None:
try:
start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
end_datetime = datetime.strptime(end_date, "%Y-%m-%d")
assert (
end_datetime > start_datetime
), "End date must be greater than start date."
assert end_datetime > start_datetime, "End date must be greater than start date."
except (ValueError, AssertionError) as e:
raise ValueError(
f"Invalid date format or range. Please use YYYY-MM-DD and ensure end_date is greater than start_date. Error: {str(e)}"
Expand Down Expand Up @@ -149,14 +150,27 @@ def get_hourly_weather(
"terrestrial_radiation",
]
url = self._build_url(latitude, longitude, start_date, end_date, variables)

cache_session = requests_cache.CachedSession(".cache", expire_after=-1)
retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
try:
response = requests.get(url)
openmeteo = openmeteo_requests.Client(session=retry_session)
response = openmeteo.weather_api(url, params={})
except requests.exceptions.Timeout:

raise TimeoutError(f"Request to OpenMeteo API timed out. URl - {url}")
data = response.json()["hourly"]

df = pd.DataFrame(data)
hourly = response[0].Hourly()
hourly_data = {"time": pd.date_range(
start=pd.to_datetime(hourly.Time(), unit="s", utc=False),
end=pd.to_datetime(hourly.TimeEnd(), unit="s", utc=False),
freq=pd.Timedelta(seconds=hourly.Interval()),
inclusive="left"
)}

for i, variable in enumerate(variables):
hourly_data[variable] = hourly.Variables(i).ValuesAsNumpy()

df = pd.DataFrame(hourly_data)
df["time"] = pd.to_datetime(df["time"])

# rename time column to date
Expand All @@ -165,5 +179,5 @@ def get_hourly_weather(
"time": "date",
}
)

return df

0 comments on commit 0c57760

Please sign in to comment.