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:
database_path: Path | str | None = None
verbose: bool = False
online: bool = False
units: Literal['metric', 'imperial'] = 'metric'
include_flags: bool = False
include_weather_types: bool = False
explain: bool = False
interpolate: bool = False
source: Literal['station', 'grid', 'auto'] = 'station'
property db: Database

Get the database instance.

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.

Parameters:
  • force (bool) – If True, rebuild even if database exists.

  • ghcn_stations (bool) – Import GHCN stations.

  • usaf_stations (bool) – Import USAF/WBAN (ISD) stations.

  • zipcodes (bool) – Import ZIP code data.

  • closest_index (bool) – Build closest stations index.

Return type:

None

get(location, target_date, elements=None)[source]

Get weather data for a location and date.

Parameters:
  • location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.

  • target_date (str | date) – Date as string (YYYY-MM-DD) or date object.

  • elements (list[str] | None) – List of weather elements to retrieve.

Returns:

WeatherResult with available weather data.

Return type:

WeatherResult

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:

list[WeatherResult]

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 pandas extra (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:
  • location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.

  • start_date (str | date) – First UTC date (YYYY-MM-DD) or date object.

  • end_date (str | date | None) – Last UTC date; defaults to start_date (single day).

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 pandas extra.

Parameters:
  • location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.

  • start_date (str | date) – First UTC date (YYYY-MM-DD) or date object.

  • end_date (str | date | None) – Last UTC date; defaults to start_date (single day).

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_range and summarizes, per element, the fraction of days with data, plus the station credited on the most days and its distance.

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) – End date (YYYY-MM-DD) or date object.

  • elements (list[str] | None) – List of weather elements to check.

Returns:

A Coverage report.

Return type:

Coverage

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:
  • input_path (str | Path) – Path to input CSV file.

  • 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).

  • lon_column (str | int | None) – Column for longitude.

  • 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 parquet extra).

  • 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:

int

info()[source]

Get database statistics.

Returns:

Dict with counts of stations and ZIP codes.

Raises:

RuntimeError – In online mode (no local database), or when the database has not been set up yet.

Return type:

dict[str, int]

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)

  • flags (dict[str, str] | None)

  • weather_types (set[str] | None)

  • stations_considered (int | None)

  • missing (dict[str, str] | None)

date

The calendar date of the observations.

Type:

datetime.date

zipcode

Queried ZIP code, when the query used one.

Type:

str | None

latitude

Latitude of the resolved query point.

Type:

float | None

longitude

Longitude of the resolved query point.

Type:

float | None

station_id

Station that supplied the first-found element.

Type:

str | None

station_name

Its human-readable name.

Type:

str | None

station_type

“GHCND” or “USAF-WBAN”.

Type:

str | None

station_distance_meters

Distance from the query point, when known.

Type:

int | None

units

Unit system of the value fields.

Type:

Literal[‘metric’, ‘imperial’]

tmax

Maximum temperature.

Type:

float | None

tmin

Minimum temperature.

Type:

float | None

tavg

Average temperature.

Type:

float | None

tobs

Temperature at observation time.

Type:

float | None

prcp

Precipitation.

Type:

float | None

snow

Snowfall (GHCN stations only; GSOD has no snowfall element).

Type:

float | None

snwd

Snow depth.

Type:

float | None

awnd

Average wind speed.

Type:

float | None

wind_gust

Peak wind gust.

Type:

float | None

dewpoint

Average dew point temperature.

Type:

float | None

sea_level_pressure

Sea-level pressure (hPa / inHg).

Type:

float | None

station_pressure

Station-level pressure (hPa / inHg).

Type:

float | None

visibility

Visibility (km / mi; GSOD stations only).

Type:

float | None

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).

Type:

dict[str, str] | None

weather_types

Present-weather phenomena for the day (e.g. {“fog”, “thunder”}), when include_weather_types is set.

Type:

set[str] | None

stations_considered

How many stations were examined to build this result, when explain is set.

Type:

int | None

missing

Per-field reason a requested value is absent (e.g. {“tmax”: “none of the 20 nearest stations …”}), when explain is set; empty when every requested field was found.

Type:

dict[str, str] | None

Coverage

Availability report from Weather.coverage(...).

class get_weather_data.Coverage(total_days, station_id=None, station_name=None, station_distance_meters=None, available=<factory>)[source]

How well a location is covered over a date range.

Parameters:
  • total_days (int)

  • station_id (str | None)

  • station_name (str | None)

  • station_distance_meters (int | None)

  • available (dict[str, int])

total_days

Number of days in the range.

Type:

int

station_id

The station credited on the most days.

Type:

str | None

station_name

Its name.

Type:

str | None

station_distance_meters

Its distance from the query point.

Type:

int | None

available

Per-field count of days with a value.

Type:

dict[str, int]

fraction(element_field)[source]

Fraction of days with data for one field (0.0 to 1.0).

Parameters:

element_field (str) – A weather value field name (e.g. “tmax”).

Returns:

Days-present / total-days, or 0.0 for an empty range.

Return type:

float

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
units: Literal['metric', 'imperial'] = 'metric'
include_weather_types: bool = False
explain: bool = False
max_stations: int = 20
zip_coordinates_loader: Callable[[], dict[str, tuple[float, float]]] | None = None
get_weather(location, target_date, elements=None)[source]

Get weather data for a location and date.

Parameters:
  • location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.

  • target_date (date) – Date to get weather for.

  • elements (list[str] | None) – Element codes to retrieve (default: all).

Returns:

WeatherResult with available data in the configured units.

Return type:

WeatherResult

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:
  • location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.

  • start_date (date) – Start date.

  • end_date (date) – End date.

  • elements (list[str] | None) – Element codes to retrieve (default: all).

Returns:

List of WeatherResult objects, one per day.

Raises:

ValueError – If the location cannot be parsed.

Return type:

list[WeatherResult]

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)

token: str | None = None
base_url: str = 'https://www.ncei.noaa.gov/cdo-web/api/v2'
timeout: float = 30.0
max_retries: int = 3
retry_delay: float = 1.0
min_request_interval: float = 0.25
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:
  • zipcode (str) – 5-digit US ZIP code.

  • start (date) – Start date (inclusive).

  • end (date) – End date (inclusive). CDO caps GHCND requests at one year; callers must chunk longer ranges.

  • datatypes (list[str] | None) – Optional GHCND element codes to restrict to.

Returns:

List of record dicts with date/datatype/station/value keys.

Return type:

list[dict[str, Any]]

get_stations(extent, start, end)[source]

Find GHCND stations within a bounding box, active in a period.

Parameters:
  • extent (tuple[float, float, float, float]) – Bounding box as (south, west, north, east) degrees.

  • start (date) – Period start; stations must have data covering it.

  • end (date) – Period end.

Returns:

List of StationInfo for matching stations.

Return type:

list[StationInfo]

get_data_for_stations(station_ids, start, end)[source]

Fetch GHCND records for specific stations and a date range.

Parameters:
  • station_ids (list[str]) – CDO station ids (e.g. “GHCND:USW00094728”).

  • start (date) – Start date (inclusive).

  • end (date) – End date (inclusive, within one year of start).

Returns:

List of record dicts with date/datatype/station/value keys.

Return type:

list[dict[str, Any]]

get_station(station_id)[source]

Fetch metadata for a station.

Parameters:

station_id (str) – CDO station id (e.g. “GHCND:USW00094728”).

Returns:

StationInfo, or None if the station is unknown.

Return type:

StationInfo | None

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.

Parameters:
Return type:

xr.Dataset | None

zip_coordinates_loader()

Load ZIP-code centroids from the cached GeoNames file.

Returns:

Mapping of 5-digit ZIP code to (lat, lon).

Return type:

dict[str, tuple[float, float]]

get_weather(location, target_date, elements=None)[source]

Get gridded weather for a location and date.

Parameters:
  • location (str | tuple[float, float]) – 5-digit US ZIP code, “lat,lon” string, or (lat, lon) tuple.

  • target_date (date) – Date to get weather for.

  • elements (list[str] | None) – Element codes to retrieve (default: all; only TMAX/TMIN/TAVG/PRCP are available from the grid).

Returns:

WeatherResult with available data in the configured units.

Return type:

WeatherResult

get_weather_range(location, start_date, end_date, elements=None)[source]

Get gridded weather 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 (date) – Start date.

  • end_date (date) – End date.

  • elements (list[str] | None) – Element codes to retrieve (default: all).

Returns:

List of WeatherResult objects, one per day.

Raises:

ValueError – If the location cannot be parsed.

Return type:

list[WeatherResult]

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.

Parameters:

path (Path | str | None)

connection()[source]

Context manager for database connection (uses pool).

Return type:

Generator[Connection, None, None]

close()[source]

Close the database connection.

Return type:

None

execute(sql, params=())[source]

Execute SQL and return all results.

Parameters:
Return type:

list[tuple[Any, …]]

execute_many(sql, params_list)[source]

Execute SQL with multiple parameter sets.

Parameters:
Return type:

None

init_schema()[source]

Initialize database schema.

Return type:

None

preload_caches()[source]

Preload all caches for maximum performance.

Return type:

None

get_station_info(station_id)[source]

Get station name and type from cache.

Parameters:

station_id (str) – Station ID.

Returns:

Tuple of (name, type) or None if not found.

Return type:

tuple[str, str] | None

insert_zipcode(zipcode, city, state, lat, lon, county='')[source]

Insert or update a ZIP code.

Parameters:
Return type:

None

insert_station(station)[source]

Insert or update a station.

Parameters:

station (Station)

Return type:

None

insert_stations_bulk(stations)[source]

Bulk insert stations.

Parameters:

stations (list[Station])

Return type:

None

get_stations(station_type=None, state=None)[source]

Get stations from database.

Parameters:
  • station_type (str | None)

  • state (str | None)

Return type:

list[Station]

get_zipcode(zipcode)[source]

Get lat/lon for a ZIP code (uses cache).

Parameters:

zipcode (str)

Return type:

tuple[float, float] | None

get_closest_stations(zipcode)[source]

Get cached closest stations for a ZIP code (uses cache).

Parameters:

zipcode (str)

Return type:

list[tuple[str, int]]

set_closest_stations_bulk(mapping)[source]

Replace the closest-stations index in a single transaction.

Parameters:

mapping (dict[str, list[tuple[str, int]]]) – ZIP code -> list of (station_id, distance_meters).

Return type:

None

get_meta(key)[source]

Read a value from the meta table.

Parameters:

key (str) – Meta key.

Returns:

Stored value, or None when absent (or table missing).

Return type:

str | None

set_meta(key, value)[source]

Write a value to the meta table.

Parameters:
  • key (str) – Meta key.

  • value (str) – Value to store.

Return type:

None

count_zipcodes()[source]

Count ZIP codes in database.

Return type:

int

count_stations(station_type=None)[source]

Count stations in database.

Parameters:

station_type (str | None)

Return type:

int

exists()[source]

Check if database file exists.

Return type:

bool

Station

Weather station data structure.

class get_weather_data.core.distance.Station(id, name, lat, lon, type, state='', elevation=None)[source]

A weather station with location.

Parameters:
id: str
name: str
lat: float
lon: float
type: str
state: str = ''
elevation: float | None = None