Access and analyze historical weather and climate data with Python.
—
The Meteostat units module provides comprehensive conversion functions for meteorological parameters, enabling easy transformation between different unit systems (metric, imperial, scientific). It includes both individual conversion functions and pre-configured unit dictionaries.
Convert temperature values between Celsius, Fahrenheit, and Kelvin scales.
def fahrenheit(value):
"""
Convert Celsius to Fahrenheit.
Parameters:
- value: float, temperature in Celsius
Returns:
float, temperature in Fahrenheit rounded to 1 decimal place
Formula: °F = (°C × 9/5) + 32
"""
def kelvin(value):
"""
Convert Celsius to Kelvin.
Parameters:
- value: float, temperature in Celsius
Returns:
float, temperature in Kelvin rounded to 1 decimal place
Formula: K = °C + 273.15
"""Convert precipitation measurements between metric and imperial units.
def inches(value):
"""
Convert millimeters to inches.
Parameters:
- value: float, precipitation in millimeters
Returns:
float, precipitation in inches rounded to 3 decimal places
Formula: inches = mm / 25.4
"""Convert distance and elevation measurements to imperial units.
def feet(value):
"""
Convert meters to feet.
Parameters:
- value: float, distance/elevation in meters
Returns:
float, distance/elevation in feet rounded to 1 decimal place
Formula: feet = meters / 0.3048
"""Convert wind speed between different velocity units.
def ms(value):
"""
Convert kilometers per hour to meters per second.
Parameters:
- value: float, wind speed in km/h
Returns:
float, wind speed in m/s rounded to 1 decimal place
Formula: m/s = km/h / 3.6
"""
def mph(value):
"""
Convert kilometers per hour to miles per hour.
Parameters:
- value: float, wind speed in km/h
Returns:
float, wind speed in mph rounded to 1 decimal place
Formula: mph = km/h × 0.6214
"""Convert numerical codes to descriptive text representations.
def direction(value):
"""
Convert wind direction in degrees to cardinal direction string.
Parameters:
- value: float, wind direction in degrees (0-360)
Returns:
str, cardinal direction (N, NE, E, SE, S, SW, W, NW)
"""
def condition(value):
"""
Convert Meteostat weather condition code to descriptive string.
Parameters:
- value: float, weather condition code (1-27)
Returns:
str, weather condition description
Condition codes:
1-4: Clear to overcast
5-6: Fog conditions
7-13: Rain and freezing rain
14-16: Snow conditions
17-22: Shower conditions
23-27: Thunderstorm and severe weather
"""Pre-configured dictionaries for converting entire datasets to specific unit systems.
# Imperial unit system
imperial: dict = {
"temp": fahrenheit, # °C to °F
"tavg": fahrenheit, # Average temperature
"tmin": fahrenheit, # Minimum temperature
"tmax": fahrenheit, # Maximum temperature
"dwpt": fahrenheit, # Dew point temperature
"prcp": inches, # mm to inches
"snow": inches, # Snow depth mm to inches
"wspd": mph, # km/h to mph
"wpgt": mph, # Wind gust km/h to mph
"distance": feet # m to feet (for station metadata)
}
# Scientific unit system
scientific: dict = {
"temp": kelvin, # °C to K
"tavg": kelvin, # Average temperature
"tmin": kelvin, # Minimum temperature
"tmax": kelvin, # Maximum temperature
"dwpt": kelvin, # Dew point temperature
"wspd": ms, # km/h to m/s
"wpgt": ms # Wind gust km/h to m/s
}from meteostat import units
# Temperature conversions
temp_c = 25.0
temp_f = units.fahrenheit(temp_c) # 77.0°F
temp_k = units.kelvin(temp_c) # 298.2 K
print(f"{temp_c}°C = {temp_f}°F = {temp_k} K")
# Precipitation conversion
precip_mm = 12.7
precip_in = units.inches(precip_mm) # 0.500 inches
print(f"{precip_mm} mm = {precip_in} inches")
# Wind speed conversions
wind_kmh = 36.0
wind_ms = units.ms(wind_kmh) # 10.0 m/s
wind_mph = units.mph(wind_kmh) # 22.4 mph
print(f"{wind_kmh} km/h = {wind_ms} m/s = {wind_mph} mph")from meteostat import units
# Wind direction conversion
wind_degrees = [0, 45, 90, 135, 180, 225, 270, 315, 360]
directions = [units.direction(deg) for deg in wind_degrees]
print("Wind directions:", dict(zip(wind_degrees, directions)))
# Weather condition conversion
condition_codes = [1, 5, 8, 15, 18, 25]
conditions = [units.condition(code) for code in condition_codes]
print("Weather conditions:", dict(zip(condition_codes, conditions)))from datetime import datetime
from meteostat import Point, Daily, units
# Get daily weather data
location = Point(40.7128, -74.0060) # New York
start = datetime(2020, 1, 1)
end = datetime(2020, 3, 31)
data = Daily(location, start, end)
# Convert to Imperial units using dictionary
imperial_data = data.convert(units.imperial)
imperial_df = imperial_data.fetch()
print("Weather data in Imperial units:")
print(imperial_df[['tavg', 'tmin', 'tmax', 'prcp', 'wspd']].head())
# Convert to Scientific units
scientific_data = data.convert(units.scientific)
scientific_df = scientific_data.fetch()
print("Weather data in Scientific units:")
print(scientific_df[['tavg', 'tmin', 'tmax', 'wspd']].head())from meteostat import Point, Hourly, units
# Create custom unit conversion dictionary
custom_units = {
'temp': units.fahrenheit, # Temperature in Fahrenheit
'wspd': units.ms, # Wind speed in m/s
'prcp': units.inches, # Precipitation in inches
'pres': lambda x: x * 0.02953, # hPa to inHg (custom function)
}
# Apply custom conversions
location = Point(51.5074, -0.1278) # London
data = Hourly(location, datetime(2020, 6, 1), datetime(2020, 6, 7))
custom_data = data.convert(custom_units)
custom_df = custom_data.fetch()
print("Custom unit combination:")
print(custom_df[['temp', 'wspd', 'prcp', 'pres']].head())from datetime import datetime
from meteostat import Point, Hourly, units
import pandas as pd
# Get hourly data with weather conditions
location = Point(52.5200, 13.4050) # Berlin
start = datetime(2020, 7, 1)
end = datetime(2020, 7, 31)
data = Hourly(location, start, end)
hourly_df = data.fetch()
# Convert wind direction to cardinal directions
hourly_df['wind_direction'] = hourly_df['wdir'].apply(units.direction)
# Convert condition codes to descriptions
hourly_df['weather_condition'] = hourly_df['coco'].apply(units.condition)
# Analyze weather patterns
weather_summary = hourly_df['weather_condition'].value_counts()
print("July 2020 weather conditions in Berlin:")
print(weather_summary)
wind_summary = hourly_df['wind_direction'].value_counts()
print("\nPrevailing wind directions:")
print(wind_summary)from meteostat import Stations, units
# Get nearby stations
stations = Stations().nearby(37.7749, -122.4194, 50000) # San Francisco
# Convert station metadata to Imperial units
imperial_stations = stations.convert({
'elevation': units.feet,
'distance': units.feet
})
station_data = imperial_stations.fetch()
print("Station elevations and distances in feet:")
print(station_data[['name', 'elevation', 'distance']].head())All conversion functions maintain appropriate precision:
# Precision specifications
temperature_precision = 1 # 1 decimal place (0.1°C/°F/K)
precipitation_precision = 3 # 3 decimal places (0.001 inches)
speed_precision = 1 # 1 decimal place (0.1 mph/m/s)
distance_precision = 1 # 1 decimal place (0.1 feet)Complete mapping of weather condition codes to descriptions:
condition_codes = {
1: "Clear", 2: "Fair", 3: "Cloudy",
4: "Overcast", 5: "Fog", 6: "Freezing Fog",
7: "Light Rain", 8: "Rain", 9: "Heavy Rain",
10: "Freezing Rain", 11: "Heavy Freezing Rain", 12: "Sleet",
13: "Heavy Sleet", 14: "Light Snowfall", 15: "Snowfall",
16: "Heavy Snowfall", 17: "Rain Shower", 18: "Heavy Rain Shower",
19: "Sleet Shower", 20: "Heavy Sleet Shower", 21: "Snow Shower",
22: "Heavy Snow Shower", 23: "Lightning", 24: "Hail",
25: "Thunderstorm", 26: "Heavy Thunderstorm", 27: "Storm"
}Unit conversions integrate seamlessly with time series processing:
# Chain operations: aggregate then convert
data = Hourly(location, start, end)
daily_imperial = data.aggregate('D').convert(units.imperial)
# Or convert then aggregate
imperial_daily = data.convert(units.imperial).aggregate('D')
# Both approaches yield equivalent resultsInstall with Tessl CLI
npx tessl i tessl/pypi-meteostat