Metadata-Version: 2.3
Name: knmi-dataset-downloader
Version: 1.16.0
Summary: A downloader for KNMI weather datasets
Author: Tibor Casteleijn
License: GPL-3.0-or-later
Requires-Dist: aiofiles==25.1.0
Requires-Dist: httpx==0.29.0
Requires-Dist: microsoft-kiota-abstractions==1.19.0
Requires-Dist: microsoft-kiota-http==1.19.0
Requires-Dist: microsoft-kiota-serialization-json==1.19.0
Requires-Dist: microsoft-kiota-serialization-text==1.19.0
Requires-Dist: microsoft-kiota-serialization-form==1.19.0
Requires-Dist: microsoft-kiota-serialization-multipart==1.19.0
Requires-Dist: tqdm==4.70.1
Requires-Python: >=3.14
Description-Content-Type: text/markdown

# KNMI Dataset Downloader

A Python package for easily downloading datasets from the KNMI (Royal Netherlands Meteorological Institute) Data Platform. This tool supports concurrent downloads and provides both a command-line interface and a Python API.

## Background

This project was inspired by my experience working at Clairify ([https://www.clairify.io](https://www.clairify.io)), where I worked extensively with KNMI datasets. After leaving, I had more time to create this tool to address the need for a more streamlined download process. The goal was to simplify dataset acquisition for Python projects, making it easier for developers and data scientists to work with KNMI's valuable meteorological data.

## Features

- Concurrent downloads for improved performance
- Progress bars for overall and per-file downloads
- Date range filtering (CLI and API translate times to UTC for the KNMI list-files API)
- Skips files that are already present on disk
- CLI and Python `async` API
- Download statistics (`DownloadStats`)
- Anonymous API key: optional automatic fetch from the KNMI developer portal (HTTP client timeout on that request)
- Kiota-generated client for the KNMI Open Data API
- **Station time series via the KNMI EDR API** (`knmi-edr`): one station, a few parameters, straight to CSV or JSON, with no NetCDF involved

## Installation

From [PyPI](https://pypi.org/project/knmi-dataset-downloader/):

```bash
pip install knmi-dataset-downloader
```

**From source** (dependencies are declared in `pyproject.toml`; lockfile is `uv.lock` if you use [uv](https://docs.astral.sh/uv/)):

```bash
git clone https://github.com/tiborrr/knmi-dataset-downloader.git
cd knmi-dataset-downloader
uv sync                  # recommended: creates .venv and installs project + dev tools
# or: pip install .
```

## Prerequisites

- **Python 3.14+** (see `requires-python` in `pyproject.toml`)
- KNMI Data Platform API key **optional** for the Open Data API (`knmi-download`): if you omit `--api-key` / `api_key`, an anonymous key is fetched from the developer portal
- An **EDR API key** for station time series (`knmi-edr`); request one at [developer.dataplatform.knmi.nl/edr-api](https://developer.dataplatform.knmi.nl/edr-api). Each KNMI API has its own key: an Open Data API key is refused by the EDR API (HTTP 403 "Access to this API has been disallowed"), and the other way around.

## Usage

### Command line

```bash
# With your own API key
knmi-download --api-key YOUR_API_KEY --start-date 2024-01-01T00:00:00 --end-date 2024-01-31T23:59:59

# Anonymous key (fetched for you)
knmi-download --start-date 2024-01-01 --end-date 2024-01-31

# Cap how many files to download
knmi-download --start-date 2024-01-01 --end-date 2024-01-31 --limit 5
```

If you omit `--start-date` / `--end-date`, the CLI defaults to the **last 1 hour 30 minutes in UTC** through **now (UTC)**.

Use `-o` / `--output-dir` to choose where files go (default: `./datasets` relative to the current working directory).

Typical options (see `knmi-download --help` for the full list):

| Option | Description |
|--------|-------------|
| `-d`, `--dataset` | Dataset name (default: `10-minute-in-situ-meteorological-observations`) |
| `-v`, `--version` | Dataset version (default: `1.0`) |
| `-c`, `--concurrent` | Max concurrent downloads (default: `10`) |
| `-s`, `--start-date` | ISO 8601 start (default: ~1h30 ago UTC) |
| `-e`, `--end-date` | ISO 8601 end (default: now UTC) |
| `--api-key` | KNMI API key (optional) |
| `-o`, `--output-dir` | Output directory (default: `./datasets`) |
| `--limit` | Maximum number of files |

### Python API

```python
import asyncio
from datetime import datetime

from knmi_dataset_downloader import download, DownloadStats


async def main() -> None:
    stats: DownloadStats = await download(
        api_key="YOUR_API_KEY",  # Optional; anonymous key is used if omitted / None
        dataset_name="10-minute-in-situ-meteorological-observations",
        version="1.0",
        max_concurrent=10,
        output_dir="path/to/output",  # default: ./datasets
        start_date=datetime(2024, 1, 1, 0, 0, 0),
        end_date=datetime(2024, 1, 31, 23, 59, 59),
        limit=5,
    )
    print(f"Total files found: {stats.total_files}")
    print(f"Files downloaded: {stats.downloaded_files}")
    print(f"Files skipped: {stats.skipped_files}")


if __name__ == "__main__":
    asyncio.run(main())
```

Public re-exports also include `DEFAULT_DATASET_NAME`, `DEFAULT_DATASET_VERSION`, `DEFAULT_MAX_CONCURRENT`, and `DEFAULT_OUTPUT_DIR` from `knmi_dataset_downloader`.

### Default dataset

The default is `10-minute-in-situ-meteorological-observations` version `1.0`, the successor of `Actuele10mindataKNMIstations` version `2`. The old dataset still exists but has received no new files since 2025-10-02; pass `--dataset Actuele10mindataKNMIstations --version 2` if you need it.

The history of the new dataset (back to 2012) was uploaded in bulk in 2025, so its modification times say nothing about the observation time. For this dataset the date range is therefore matched against the time stamp in the file name (`KMDS__OPER_P___10M_OBS_L2_YYYYmmddHHMM.nc`, UTC, both ends inclusive). Other datasets are still filtered on modification time.

## Station time series (EDR API)

For one value per 10 minutes from one station, the [KNMI EDR API](https://developer.dataplatform.knmi.nl/edr-api) is much simpler than downloading NetCDF files: it returns the series for a station and parameters directly. `knmi-edr` wraps it.

The API key comes from `--api-key` or the `KNMI_EDR_API_KEY` environment variable.

```bash
export KNMI_EDR_API_KEY=...            # an EDR key, not an Open Data key

# What is there?
knmi-edr collections                   # 10-minute, hourly, daily, monthly, annual, ...
knmi-edr stations --search hei         # 0-20000-0-06278  278  Heino  52.4344  6.2589
knmi-edr parameters --search radiation # qg  W/m²  Global Solar Radiation Mean ...

# Global solar radiation (qg) and sunshine (ss) in Heino, as CSV
knmi-edr series --station Heino -p qg,ss \
    --start 2026-11-26T06:00 --end 2026-12-03T17:00 -o heino.csv

# Same station by KNMI number, as JSON on stdout
knmi-edr series --station 278 -p qg -f json
```

| `series` option | Description |
|-----------------|-------------|
| `--station` | Station name (`Heino`, case-insensitive, also a unique part of the name), KNMI number (`278`), WMO id (`06278`) or WIGOS id (`0-20000-0-06278`) |
| `-p`, `--parameter` | Parameter name (`qg`); repeat or comma-separate for more. Case is ignored when that is unambiguous |
| `-C`, `--collection` | Collection (default: `10-minute-in-situ-meteorological-observations`; also e.g. `hourly-in-situ-meteorological-observations` or `daily-in-situ-meteorological-observations-validated`) |
| `-s`, `--start` / `-e`, `--end` | ISO 8601, both inclusive; without an offset the time is **UTC**. Default: the last 24 hours |
| `-f`, `--format` | `csv` or `json` (default: from the `-o` extension, else `csv`) |
| `-o`, `--output` | Output file (default: stdout) |

Good to know:

- **Time stamps** are UTC and mark the **end** of the measuring interval: `2026-12-03T07:20:00Z` for `qg` is the mean over 07:10–07:20. The 10-minute data runs about 20 minutes behind real time and goes back to 2012-01-01.
- **Missing values** are empty in CSV and `null` in JSON.
- **Parameters** differ per collection (`qg` W/m² and `ss` minutes in the 10-minute set; `Q` J/cm² in the daily set); names and descriptions are in English.
- **Long ranges** are fetched in several requests: the API allows at most 300,000 values (time points × parameters) per request.

CSV columns are `time,station_id,station_name,<parameter>...`. JSON holds the station, parameter metadata (label, description, unit) and a `data` list of records.

### Python API

```python
import asyncio
from datetime import UTC, datetime

from knmi_dataset_downloader import EdrClient, fetch_timeseries, write_csv


async def main() -> None:
    start = datetime(2026, 11, 26, 6, 0, tzinfo=UTC)
    end = datetime(2026, 12, 3, 17, 0, tzinfo=UTC)

    # One call
    series = await fetch_timeseries("EDR_API_KEY", "Heino", ["qg"], start, end)
    for row in series.rows():  # {"time": datetime, "qg": float | None}
        print(row["time"], row["qg"])

    # Or with a client, to look things up first
    async with EdrClient("EDR_API_KEY") as client:
        station = await client.find_station(
            "278"
        )  # Station(id="0-20000-0-06278", name="Heino", ...)
        radiation = await client.find_parameter(
            "qg"
        )  # Parameter(name="qg", unit="W/m²", ...)
        series = await client.get_timeseries(station, [radiation], start, end)
        with open("heino.csv", "w", newline="", encoding="utf-8") as fh:
            write_csv(series, fh)


asyncio.run(main())
```

`TimeSeries` has `times` (aware UTC datetimes) and `values` (`{parameter: [float | None, ...]}`) aligned with them. Errors are raised as `EdrError`; an unknown or ambiguous station or parameter raises `NotFoundError` / `AmbiguousMatchError` (both subclasses) listing the candidates.

## Download statistics

Each run reports:

- Total files matching the query
- Skipped (already on disk)
- Downloaded
- Failures (with names in `stats.failed_files`)
- Total bytes downloaded

## Configuration

There is **no** `DATASET_OUTPUT_DIR` environment variable in this package. Outputs go to:

- **Default:** `./datasets` (see `DEFAULT_OUTPUT_DIR` in `knmi_dataset_downloader.defaults`), or
- **CLI:** `--output-dir` / `-o`, or
- **API:** `output_dir=` on `download()`.

## Error handling

- Existing files are skipped (not re-downloaded by default).
- Partial files are removed if a download fails.
- Failures are logged and listed on `DownloadStats.failed_files`.

Heavy use of the **anonymous** Open Data API can result in **HTTP 429**; KNMI may require a **cooldown** (on the order of an hour) before retrying.

## Developing

- **Tests:** `pytest` with `pytest-asyncio` (`uv run pytest` or `pytest tests` with dev deps installed).
- **Lint / types:** `uv run ruff check src tests`, `uv run basedpyright src tests` (see `pyproject.toml`).
- **Integration tests** call the real KNMI API; they may **skip** on 429. The EDR tests in `tests/integration/test_edr.py` are skipped unless `KNMI_EDR_API_KEY` is set.

### KNMI Open Data API client (Kiota)

The HTTP client under `src/knmi_dataset_downloader/knmi_dataset_api` is generated with [Kiota](https://github.com/microsoft/kiota) from the KNMI OpenAPI description. Workspace metadata lives in [`.kiota/workspace.json`](.kiota/workspace.json) (and [`.kiota/apimanifest.json`](.kiota/apimanifest.json)).

To **explore** the API surface and OpenAPI in the editor, install the [Kiota extension for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=ms-graph.kiota), open this repository, and use the extension’s explorer (e.g. browse the description and see how it maps to the generated request builders). Regenerating the client is optional; if you need to, use the Kiota CLI or the extension’s generate flow with that workspace configuration.

## Contributing

Contributions are welcome. Please open a Pull Request; for larger changes, open an issue first.

## License

This project is licensed under the GNU General Public License v3.0 or later — see the [LICENSE](LICENSE) file.

## Acknowledgments

- KNMI for the Data Platform API
- Async I/O via `asyncio` and `httpx`

## Support

Problems or suggestions: [open an issue](https://github.com/tiborrr/knmi-dataset-downloader/issues).
