API Reference¶
Weather Class¶
The main interface for getting weather data.
- class get_weather_data.Weather(database_path=None, verbose=False, online=False, units='metric', include_flags=False, include_weather_types=False, explain=False, interpolate=False, source='station', _db=None, _lookup=None, _online_lookup=None, _grid=None, _hourly=None)[source]¶
High-level API for fetching weather data.
This class provides a simple interface for: - Setting up the station database - Looking up weather data for ZIP codes - Processing CSV files
Example
weather = Weather() weather.setup() result = weather.get(“10001”, “2024-01-15”)
With online=True, get() and get_range() query the NOAA CDO API directly — no setup() download (just a small cached ZIP-coordinates file), but NCDC_TOKEN must be set.
- Parameters:
verbose (bool)
online (bool)
units (Literal['metric', 'imperial'])
include_flags (bool)
include_weather_types (bool)
explain (bool)
interpolate (bool)
source (Literal['station', 'grid', 'auto'])
_db (Database | None)
_lookup (WeatherLookup | None)
_online_lookup (OnlineLookup | None)
_grid (GriddedLookup | None)
_hourly (HourlyLookup | None)
- property lookup: WeatherLookup¶
Get the weather lookup instance.
- property grid: GriddedLookup¶
Get the nClimGrid gridded-lookup instance.
- property hourly: HourlyLookup¶
Get the ISD-Lite hourly-lookup instance.
- setup(force=False, ghcn_stations=True, usaf_stations=True, zipcodes=True, closest_index=True)[source]¶
Set up the database with station and ZIP code data.
This downloads station lists and ZIP code data, then builds an index of closest stations for each ZIP code.
- get(location, target_date, elements=None)[source]¶
Get weather data for a location and date.
- Parameters:
- Returns:
WeatherResult with available weather data.
- Return type:
- get_range(location, start_date, end_date, elements=None)[source]¶
Get weather data for a location over a date range.
- Parameters:
location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.
start_date (str | date) – Start date as string (YYYY-MM-DD) or date object.
end_date (str | date) – End date as string (YYYY-MM-DD) or date object.
elements (list[str] | None) – List of weather elements to retrieve.
- Returns:
List of WeatherResult objects, one per day.
- Return type:
- get_frame(location, start_date, end_date=None, elements=None)[source]¶
Get weather for a location as a pandas DataFrame.
One row per day, metadata columns followed by the weather value columns (in the configured units). Requires the
pandasextra (pip install get-weather-data[pandas]).- Parameters:
location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.
start_date (str | date) – Start date (YYYY-MM-DD) or date object.
end_date (str | date | None) – End date; defaults to start_date (single day).
elements (list[str] | None) – List of weather elements to retrieve.
- Returns:
A tidy DataFrame of the results.
- Raises:
ImportError – If pandas is not installed.
- Return type:
pd.DataFrame
- get_hourly(location, start_date, end_date=None)[source]¶
Get hourly observations for a location (ISD-Lite).
Resolves the nearest USAF-WBAN station and reads hourly ISD-Lite data. Requires the local database (
setup()); there is no online equivalent for hourly data.- Parameters:
- Returns:
One HourlyResult per available hour, in time order (UTC).
- Raises:
ValueError – If this Weather was created with online=True.
- Return type:
list[HourlyResult]
- get_hourly_frame(location, start_date, end_date=None)[source]¶
Get hourly observations as a pandas DataFrame.
One row per hour, metadata columns followed by the value columns (in the configured units). Requires the
pandasextra.- Parameters:
- Returns:
A tidy DataFrame of the hourly results.
- Raises:
ImportError – If pandas is not installed.
- Return type:
pd.DataFrame
- coverage(location, start_date, end_date, elements=None)[source]¶
Report how well a location is covered over a date range.
Runs the same lookups as
get_rangeand summarizes, per element, the fraction of days with data, plus the station credited on the most days and its distance.- Parameters:
- Returns:
A Coverage report.
- Return type:
- process_csv(input_path, output_path, zipcode_column='zip', lat_column=None, lon_column=None, date_column=None, year_column='year', month_column='month', day_column='day', output_format=None, parallel=True, max_workers=None)[source]¶
Process a CSV file and add weather data.
- Parameters:
output_path (str | Path) – Path to output file (CSV or Parquet).
zipcode_column (str | int) – Column name or index for ZIP code.
lat_column (str | int | None) – Column for latitude (used with lon_column).
date_column (str | int | None) – Column name or index for date (YYYY-MM-DD).
year_column (str | int | None) – Column for year (if no date_column).
month_column (str | int | None) – Column for month (if no date_column).
day_column (str | int | None) – Column for day (if no date_column).
output_format (str | None) – “csv” or “parquet”; inferred from the output path suffix when None (Parquet needs the
parquetextra).parallel (bool) – Use parallel processing for faster execution.
max_workers (int | None) – Number of worker threads (default: CPU count, max 8).
- Returns:
Number of rows processed.
- Raises:
ValueError – If this Weather was created with online=True — batch jobs need the local database (the CDO API allows only 10,000 requests per day).
- Return type:
WeatherResult¶
Data returned from weather queries. Value fields are floats in the
unit system named by units (metric: °C/mm/m/s; imperial:
°F/in/mph); None means no station reported that element.
- class get_weather_data.WeatherResult(date, zipcode=None, latitude=None, longitude=None, station_id=None, station_name=None, station_type=None, station_distance_meters=None, units='metric', tmax=None, tmin=None, tavg=None, tobs=None, prcp=None, snow=None, snwd=None, awnd=None, wind_gust=None, dewpoint=None, sea_level_pressure=None, station_pressure=None, visibility=None, flags=None, weather_types=None, stations_considered=None, missing=None)[source]¶
Weather data for one location and date.
Value fields are in the unit system named by
units: metric — tmax/tmin/tavg/tobs in °C, prcp/snow/snwd in mm, awnd in m/s; imperial — °F, inches, mph. Fields are None when no station reported that element.- Parameters:
date (date)
zipcode (str | None)
latitude (float | None)
longitude (float | None)
station_id (str | None)
station_name (str | None)
station_type (str | None)
station_distance_meters (int | None)
units (Literal['metric', 'imperial'])
tmax (float | None)
tmin (float | None)
tavg (float | None)
tobs (float | None)
prcp (float | None)
snow (float | None)
snwd (float | None)
awnd (float | None)
wind_gust (float | None)
dewpoint (float | None)
sea_level_pressure (float | None)
station_pressure (float | None)
visibility (float | None)
stations_considered (int | None)
- date¶
The calendar date of the observations.
- Type:
- units¶
Unit system of the value fields.
- Type:
Literal[‘metric’, ‘imperial’]
- flags¶
Per-field GHCN quality-control flag, when include_flags is set; a blank flag means the value passed all QC checks (GHCN stations only).
- weather_types¶
Present-weather phenomena for the day (e.g. {“fog”, “thunder”}), when include_weather_types is set.
Coverage¶
Availability report from Weather.coverage(...).
OnlineLookup¶
Database-free lookup backed by the NOAA CDO Web Services v2 API
(used when Weather(online=True); requires NCDC_TOKEN). Stations
are resolved from ZIP centroids (small cached GeoNames file), nearest
first, so results carry real station distances.
- class get_weather_data.weather.online.OnlineLookup(client=<factory>, units='metric', include_weather_types=False, explain=False, max_stations=20, zip_coordinates_loader=None, _zip_coords=None, _station_lists=<factory>)[source]¶
Look up weather for locations via the CDO API.
- Parameters:
- client: NOAAClient¶
- get_weather(location, target_date, elements=None)[source]¶
Get weather data for a location and date.
- Parameters:
- Returns:
WeatherResult with available data in the configured units.
- Return type:
- get_weather_range(location, start_date, end_date, elements=None)[source]¶
Get weather data for a location over a date range.
The range is fetched in at most one API request per calendar year (CDO caps GHCND requests at one year), never per day.
- Parameters:
- Returns:
List of WeatherResult objects, one per day.
- Raises:
ValueError – If the location cannot be parsed.
- Return type:
NOAAClient¶
Low-level CDO v2 API client.
- class get_weather_data.api.NOAAClient(token=None, base_url='https://www.ncei.noaa.gov/cdo-web/api/v2', timeout=30.0, max_retries=3, retry_delay=1.0, min_request_interval=0.25, _last_request=0.0)[source]¶
Client for NOAA CDO Web Services v2.
- Parameters:
token (str | None) – CDO API token. Falls back to the NCDC_TOKEN environment variable (via config) when not given.
base_url (str) – API base URL.
timeout (float) – Per-request timeout in seconds.
max_retries (int) – Retries for rate-limit/server/transport errors.
retry_delay (float) – Base delay for exponential backoff, in seconds.
min_request_interval (float) – Client-side throttle between requests, in seconds (the API allows 5 requests per second).
_last_request (float)
- get_data(zipcode, start, end, datatypes=None)[source]¶
Fetch GHCND records for a ZIP code and date range.
Values come back in raw GHCN units (tenths for temperatures and precipitation), matching the bulk-file backend.
- Parameters:
- Returns:
List of record dicts with date/datatype/station/value keys.
- Return type:
- get_stations(extent, start, end)[source]¶
Find GHCND stations within a bounding box, active in a period.
GriddedLookup¶
nClimGrid gridded backend (Weather(source="grid"); needs the
grid extra). Any contiguous-US point returns temperature and
precipitation.
- class get_weather_data.weather.gridded.GriddedLookup(units='metric', dataset_opener=<function _open_opendap>, zip_coordinates_loader=<function zip_centroids>, _zip_coords=None)[source]¶
Look up weather for any CONUS point from the nClimGrid grid.
- Parameters:
- dataset_opener(month)¶
Open one monthly nClimGrid dataset over OPeNDAP.
- zip_coordinates_loader()¶
Load ZIP-code centroids from the cached GeoNames file.
- get_weather(location, target_date, elements=None)[source]¶
Get gridded weather for a location and date.
- Parameters:
- Returns:
WeatherResult with available data in the configured units.
- Return type:
- get_weather_range(location, start_date, end_date, elements=None)[source]¶
Get gridded weather for a location over a date range.
- Parameters:
- Returns:
List of WeatherResult objects, one per day.
- Raises:
ValueError – If the location cannot be parsed.
- Return type:
Database¶
Low-level database operations.
- class get_weather_data.core.database.Database(path=None)[source]¶
SQLite database for weather station and ZIP code data.
Uses connection pooling and caches station metadata for efficiency.
- connection()[source]¶
Context manager for database connection (uses pool).
- Return type:
Generator[Connection, None, None]
- insert_station(station)[source]¶
Insert or update a station.
- Parameters:
station (Station)
- Return type:
None
- set_closest_stations_bulk(mapping)[source]¶
Replace the closest-stations index in a single transaction.
Station¶
Weather station data structure.