Last active
October 29, 2024 18:31
-
-
Save villares/a9e2fb9f393d4b211765d0572833678a to your computer and use it in GitHub Desktop.
Weather stuff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from https://open-meteo.com/en/docs#latitude=-23.5475&longitude=-46.6361&hourly=temperature_2m,rain | |
import openmeteo_requests # pip install openmeteo-requests | |
import requests_cache # install requests-cache | |
import pandas as pd # install pandas | |
from retry_requests import retry # install retry-requests | |
# Setup the Open-Meteo API client with cache and retry on error | |
cache_session = requests_cache.CachedSession('.cache', expire_after = 3600) | |
retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2) | |
openmeteo = openmeteo_requests.Client(session = retry_session) | |
# Make sure all required weather variables are listed here | |
# The order of variables in hourly or daily is important to assign them correctly below | |
url = "https://api.open-meteo.com/v1/forecast" | |
params = { # São Paulo | |
"latitude": -23.5475, | |
"longitude": -46.6361, | |
"hourly": ["temperature_2m", "rain"] | |
} | |
responses = openmeteo.weather_api(url, params=params) | |
# Process first location. Add a for-loop for multiple locations or weather models | |
response = responses[0] | |
print(f"Coordinates {response.Latitude()}°N {response.Longitude()}°E") | |
print(f"Elevation {response.Elevation()} m asl") | |
print(f"Timezone {response.Timezone()} {response.TimezoneAbbreviation()}") | |
print(f"Timezone difference to GMT+0 {response.UtcOffsetSeconds()} s") | |
# Process hourly data. The order of variables needs to be the same as requested. | |
hourly = response.Hourly() | |
hourly_temperature_2m = hourly.Variables(0).ValuesAsNumpy() | |
hourly_rain = hourly.Variables(1).ValuesAsNumpy() | |
hourly_data = {"date": pd.date_range( | |
start = pd.to_datetime(hourly.Time(), unit = "s", utc = True), | |
end = pd.to_datetime(hourly.TimeEnd(), unit = "s", utc = True), | |
freq = pd.Timedelta(seconds = hourly.Interval()), | |
inclusive = "left" | |
)} | |
hourly_data["temperature_2m"] = hourly_temperature_2m | |
hourly_data["rain"] = hourly_rain | |
hourly_dataframe = pd.DataFrame(data = hourly_data) | |
print(hourly_dataframe) | |
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests # pip install | |
import tomllib # if on Python 3.11+ or install and `import tomli as tomlli` | |
""" | |
with open('/home/villares/api_tokens', 'rb') as f: | |
api_tokens = tomllib.load(f) | |
API_KEY = api_tokens['openweathermap']['api_key'] | |
""" | |
API_KEY = 'your API key' # get one at www.openweathermap.org | |
# Set the latitude and longitude for the location you're interested in | |
latitude = '23.5475' | |
longitude = '-46.6361' | |
# URL for the OpenWeather Current Weather Data API | |
url = 'https://api.openweathermap.org/data/2.5/weather' | |
url_params = f'?lat={latitude}&lon={longitude}&units=metric&appid={API_KEY}' | |
# Make a request to the OpenWeather API | |
response = requests.get(url + url_params) | |
# Check if the request was successful | |
if response.status_code == 200: | |
# Convert the response to JSON | |
data = response.json() | |
# Extract and print the temperature, weather description, and more | |
temperature = data['main']['temp'] | |
weather_description = data['weather'][0]['description'] | |
humidity = data['main']['humidity'] | |
wind_speed = data['wind']['speed'] | |
print(f'Temperature: {temperature} C') # &units=metric for C imperial for F | |
print(f'Weather Description: {weather_description}') | |
print(f'Humidity: {humidity}%') | |
print(f'Wind Speed: {wind_speed} meter/sec') | |
else: | |
print(response.status_code, 'Failed to retrieve data') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Temperature: 26.35 C
Weather Description: moderate rain
Humidity: 79%
Wind Speed: 9.33 meter/sec
{'coord': {'lon': -46.6361, 'lat': 23.5475}, 'weather': [{'id': 501, 'main': 'Rain', 'description': 'moderate rain', 'icon': '10d'}], 'base': 'stations', 'main': {'temp': 26.35, 'feels_like': 26.35, 'temp_min': 26.35, 'temp_max': 26.35, 'pressure': 1012, 'humidity': 79, 'sea_level': 1012, 'grnd_level': 1012}, 'visibility': 8093, 'wind': {'speed': 9.33, 'deg': 193, 'gust': 10.73}, 'rain': {'1h': 1.14}, 'clouds': {'all': 97}, 'dt': 1730226208, 'sys': {'sunrise': 1730193040, 'sunset': 1730233777}, 'timezone': -10800, 'id': 0, 'name': '', 'cod': 200}