CimisClient
The main client class for interacting with the CIMIS API.
- class python_cimis.CimisClient(app_key: str, timeout: int = 30)[source]
Bases:
objectMain client for accessing the California Irrigation Management Information System (CIMIS) API.
This client provides methods to: - Fetch weather data by station, zip code, coordinates, or address - Retrieve station information - Get zip code information - Export data to CSV format with all available columns - Auto-generate filenames based on station names and dates
- __init__(app_key: str, timeout: int = 30)[source]
Initialize the CIMIS client.
- Parameters:
app_key – Your CIMIS API application key
timeout – Request timeout in seconds (default: 30)
- property BASE_URL
Base URL for CIMIS API (for backward compatibility).
- property DEFAULT_DAILY_DATA_ITEMS
Default daily data items (for backward compatibility).
- property DEFAULT_HOURLY_DATA_ITEMS
Default hourly data items (for backward compatibility).
- get_data(targets: str | List[str], start_date: str | date | datetime, end_date: str | date | datetime, data_items: List[str] | None = None, unit_of_measure: str = 'E', prioritize_scs: bool = True) WeatherData[source]
Get weather data from CIMIS.
- Parameters:
targets – Station numbers, zip codes, coordinates, or addresses
start_date – Start date (YYYY-MM-DD format, date, or datetime)
end_date – End date (YYYY-MM-DD format, date, or datetime)
data_items – List of data items to retrieve (uses default if None)
unit_of_measure – ‘E’ for English or ‘M’ for Metric
prioritize_scs – Whether to prioritize SCS data for zip codes
- Returns:
WeatherData object containing the response
- get_daily_data(targets: str | List[str], start_date: str | date | datetime, end_date: str | date | datetime, data_items: List[str] | None = None, unit_of_measure: str = 'Metric', prioritize_scs: bool = True, csv: bool = False, filename: str | Path | None = None) WeatherData | tuple[WeatherData, str][source]
Get daily weather data from CIMIS.
This method returns only daily data records with all daily data items by default.
- Parameters:
targets – Station numbers, zip codes, coordinates, or addresses
start_date – Start date for data retrieval
end_date – End date for data retrieval
data_items – List of data items to retrieve (uses default daily items if None)
unit_of_measure – ‘Metric’ for Metric units (default) or ‘English’ for English units
prioritize_scs – Whether to prioritize SCS data for zip codes
csv – If True, automatically export to CSV with auto-generated filename
filename – Custom filename for CSV export (only used if csv=True)
- Returns:
WeatherData object containing only daily records if csv=False, or tuple of (WeatherData, csv_filename) if csv=True
- get_hourly_data(targets: str | List[str], start_date: str | date | datetime, end_date: str | date | datetime, data_items: List[str] | None = None, unit_of_measure: str = 'Metric', csv: bool = False, filename: str | Path | None = None) WeatherData | tuple[WeatherData, str][source]
Get hourly weather data from CIMIS.
Note: Hourly data is only available from WSN stations, not SCS. Returns only hourly data records (no daily data mixed in).
- Parameters:
targets – Station numbers, zip codes, coordinates, or addresses
start_date – Start date for data retrieval
end_date – End date for data retrieval
data_items – List of data items to retrieve (uses default if None)
unit_of_measure – ‘Metric’ for Metric units (default) or ‘English’ for English units
csv – If True, automatically export to CSV with auto-generated filename (hourly only)
filename – Custom filename for CSV export (only used if csv=True)
- Returns:
WeatherData object if csv=False, or tuple of (WeatherData, csv_filename) if csv=True Note: WeatherData will contain only hourly records
- get_stations(station_number: str | None = None) List[Station][source]
Get station information.
- Parameters:
station_number – Specific station number (gets all stations if None)
- Returns:
List of Station objects
- get_station_zip_codes(zip_code: str | None = None) List[ZipCode][source]
Get station zip code information.
- Parameters:
zip_code – Specific zip code (gets all zip codes if None)
- Returns:
List of ZipCode objects
- get_spatial_zip_codes(zip_code: str | None = None) List[SpatialZipCode][source]
Get spatial zip code information.
- Parameters:
zip_code – Specific zip code (gets all zip codes if None)
- Returns:
List of SpatialZipCode objects
- export_to_csv(weather_data: WeatherData, filename: str | Path | None = None, include_all_columns: bool = True, separate_daily_hourly: bool = True) str[source]
Export weather data to CSV file with properly formatted data columns. Uses automatic filename generation based on station names and dates by default.
- Parameters:
weather_data – WeatherData object to export
filename – Output CSV filename (auto-generated if None)
include_all_columns – Whether to include all possible data columns
separate_daily_hourly – Whether to separate daily and hourly data into different files
- Returns:
Path to the created CSV file(s)
- export_stations_to_csv(stations: List[Station], filename: str | Path | None = None) str[source]
Export station information to CSV file. Uses automatic filename generation based on stations data by default.
- Parameters:
stations – List of Station objects to export
filename – Output CSV filename (auto-generated if None)
- Returns:
Path to the created CSV file
- get_data_and_export_csv(targets: str | List[str], start_date: str | date | datetime, end_date: str | date | datetime, filename: str | Path | None = None, data_items: List[str] | None = None, unit_of_measure: str = 'E', prioritize_scs: bool = True) tuple[WeatherData, str][source]
Convenience method to get data and immediately export to CSV. Uses automatic filename generation based on station names and dates by default.
- Parameters:
targets – Station numbers, zip codes, coordinates, or addresses
start_date – Start date
end_date – End date
filename – Output CSV filename (auto-generated if None)
data_items – List of data items to retrieve (uses default if None)
unit_of_measure – ‘E’ for English or ‘M’ for Metric
prioritize_scs – Whether to prioritize SCS data for zip codes
- Returns:
Tuple of (WeatherData object, path to created CSV file)
Usage Examples
Basic Usage
from python_cimis import CimisClient
import os
# Initialize client
client = CimisClient(app_key=os.getenv('CIMIS_API_KEY'))
# Get daily weather data
weather_data = client.get_daily_data(
targets=[2, 8, 127],
start_date="2023-06-01",
end_date="2023-06-07"
)
# Export to CSV
csv_file = client.export_to_csv(weather_data)
Advanced Configuration
# Custom timeout and configuration
client = CimisClient(
app_key="your-api-key",
timeout=60 # 60 second timeout
)
# Get specific data items only
weather_data = client.get_daily_data(
targets=[2],
start_date="2023-06-01",
end_date="2023-06-30",
data_items=["day-air-tmp-avg", "day-eto", "day-precip"],
unit_of_measure="M", # Metric units
prioritize_scs=True # Prefer Spatial CIMIS System data
)
Target Types
The client supports multiple target types:
# Station numbers
weather_data = client.get_daily_data(
targets=[2, 8, 127],
start_date="2023-06-01",
end_date="2023-06-07"
)
# Zip codes
weather_data = client.get_daily_data(
targets=["95823", "94503"],
start_date="2023-06-01",
end_date="2023-06-07"
)
# Coordinates
weather_data = client.get_daily_data(
targets=["lat=38.5816,lng=-121.4944"],
start_date="2023-06-01",
end_date="2023-06-07"
)
# Addresses
weather_data = client.get_daily_data(
targets=["addr-name=Capitol,addr=1315 10th Street Sacramento, CA 95814"],
start_date="2023-06-01",
end_date="2023-06-07"
)
# Mixed types
weather_data = client.get_daily_data(
targets=[2, "95823", "lat=38.5816,lng=-121.4944"],
start_date="2023-06-01",
end_date="2023-06-07"
)
Error Handling
from python_cimis.exceptions import CimisAPIError, CimisConnectionError, CimisAuthenticationError
try:
weather_data = client.get_daily_data(
targets=[2],
start_date="2023-06-01",
end_date="2023-06-07"
)
except CimisAuthenticationError:
print("Invalid API key")
except CimisConnectionError as e:
print(f"Connection error: {e.message}")
except CimisAPIError as e:
print(f"API error: {e.message} (Code: {e.error_code})")
Station Discovery
# Get all stations
all_stations = client.get_stations()
print(f"Total stations: {len(all_stations)}")
# Get specific station
station_2 = client.get_stations(station_number="2")
if station_2:
station = station_2[0]
print(f"Station 2: {station.name} in {station.city}")
# Find active ETo stations
active_eto_stations = [
s for s in all_stations
if s.is_active and s.is_eto_station
]
# Get zip code coverage
wsn_zips = client.get_station_zip_codes()
scs_zips = client.get_spatial_zip_codes()
CSV Export Options
# Auto-generated filename
csv_file = client.export_to_csv(weather_data)
print(f"Exported to: {csv_file}")
# Custom filename
client.export_to_csv(weather_data, filename="my_weather_data.csv")
# Export station information
stations = client.get_stations()
station_csv = client.export_stations_to_csv(stations, filename="stations.csv")
Performance Tips
# For large date ranges, split into smaller chunks
from datetime import date, timedelta
def get_large_dataset(client, targets, start_date, end_date, chunk_days=30):
"""Get large dataset by splitting into chunks."""
all_records = []
current_date = start_date
while current_date <= end_date:
chunk_end = min(current_date + timedelta(days=chunk_days), end_date)
weather_data = client.get_daily_data(
targets=targets,
start_date=current_date,
end_date=chunk_end
)
all_records.extend(weather_data.get_all_records())
current_date = chunk_end + timedelta(days=1)
return all_records
# Use specific data items for faster responses
weather_data = client.get_daily_data(
targets=[2],
start_date="2023-01-01",
end_date="2023-12-31",
data_items=["day-air-tmp-avg", "day-eto"] # Only what you need
)