Files
aimsight-app/weather/meteoswiss.py
T
maximeandClaude Opus 5.5 eaa124f9f5 Weather: the MeteoSwiss measurements at a place over a past range
weather/meteoswiss.py <place> <start> <end>: the hourly values of the
nearest SwissMetNet station (precipitation, temperature, humidity, wind,
pressure, sunshine, radiation, snow), from the MeteoSwiss Open Data, as CSV.
The place is a Swiss name (swisstopo search) or lat,lon; times in UTC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:54:28 +01:00

160 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""The weather measured by MeteoSwiss at the station nearest to a place, over a past range.
python3 weather/meteoswiss.py <place> <start> <end> [--out FILE]
<place> is a Swiss place name ("Genève", "Lausanne") or coordinates "lat,lon" (WGS84);
<start> and <end> are dates YYYY-MM-DD or YYYY-MM-DDTHH:MM, in UTC, <end> excluded.
The output is an hourly CSV (stdout by default), one row per hour.
The source is the Open Data of MeteoSwiss: the automatic weather stations SwissMetNet,
the real measurements (not a model), quality-checked except for the current day
(https://opendatadocs.meteoswiss.ch/a-data-groundbased/a1-automatic-weather-stations).
The place name is resolved by the search service of swisstopo (api3.geo.admin.ch).
No key, no dependency outside the standard library.
"""
import argparse
import csv
import io
import json
import math
import sys
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
BASE = "https://data.geo.admin.ch/ch.meteoschweiz.ogd-smn"
STAC_ITEM = "https://data.geo.admin.ch/api/stac/v1/collections/ch.meteoschweiz.ogd-smn/items/{}"
GEOCODER = "https://api3.geo.admin.ch/rest/services/api/SearchServer"
# MeteoSwiss parameter -> column of the output (hourly values).
PARAMETERS = {
"rre150h0": "precipitation_mm", # hourly total
"tre200h0": "temperature_c", # air at 2 m, hourly mean
"ure200h0": "humidity_pct", # relative, at 2 m, hourly mean
"fu3010h0": "wind_speed_kmh", # hourly mean
"fu3010h1": "wind_gust_kmh", # hourly max of the gusts
"dkl010h0": "wind_direction_deg", # hourly mean
"prestah0": "pressure_hpa", # at the station (QFE), hourly mean
"sre000h0": "sunshine_min", # hourly total
"gre000h0": "global_radiation_wm2", # hourly mean
"htoauths": "snow_depth_cm", # instantaneous, not at every station
}
def fetch(url):
request = urllib.request.Request(url, headers={"User-Agent": "aimsight-weather"})
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
def parse_time(text):
for form in ("%Y-%m-%dT%H:%M", "%Y-%m-%d"):
try:
return datetime.strptime(text, form).replace(tzinfo=timezone.utc)
except ValueError:
pass
raise argparse.ArgumentTypeError(f"not a date YYYY-MM-DD[THH:MM]: {text}")
def locate(place):
"""(lat, lon, label) of a place name or of "lat,lon"."""
parts = place.split(",")
if len(parts) == 2:
try:
lat, lon = float(parts[0]), float(parts[1])
return lat, lon, f"{lat},{lon}"
except ValueError:
pass
query = urllib.parse.urlencode({"searchText": place, "type": "locations", "limit": 1, "sr": 4326})
results = json.loads(fetch(f"{GEOCODER}?{query}"))["results"]
if not results:
sys.exit(f"place not found: {place}")
attrs = results[0]["attrs"]
label = attrs["label"].replace("<b>", "").replace("</b>", "").split("\n")[0].strip()
return attrs["lat"], attrs["lon"], label
def distance_km(lat1, lon1, lat2, lon2):
p1, p2 = math.radians(lat1), math.radians(lat2)
a = (math.sin((p2 - p1) / 2) ** 2
+ math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2)
return 2 * 6371 * math.asin(math.sqrt(a))
def nearest_station(lat, lon):
text = fetch(f"{BASE}/ogd-smn_meta_stations.csv").decode("latin-1")
stations = list(csv.DictReader(io.StringIO(text), delimiter=";"))
station = min(stations, key=lambda s: distance_km(
lat, lon, float(s["station_coordinates_wgs84_lat"]), float(s["station_coordinates_wgs84_lon"])))
station["distance_km"] = distance_km(
lat, lon, float(station["station_coordinates_wgs84_lat"]), float(station["station_coordinates_wgs84_lon"]))
return station
def files_for(station, start, end):
"""The hourly files of the station that cover [start, end): historical by decade, recent, now."""
item = json.loads(fetch(STAC_ITEM.format(station.lower())))
names = [n for n in item["assets"] if f"_{station.lower()}_h_" in n]
chosen = []
for name in names:
stem = name.rsplit(".", 1)[0]
if "_historical_" in stem:
first, last = (int(y) for y in stem.rsplit("_", 1)[1].split("-"))
if start.year <= last and end.year >= first:
chosen.append(name)
elif stem.endswith("_recent"): # from January 1 of the current year to yesterday
if end.year >= datetime.now(timezone.utc).year - 1:
chosen.append(name)
elif stem.endswith("_now"): # since midnight, not yet quality-checked
if end > datetime.now(timezone.utc) - timedelta(days=1):
chosen.append(name)
return [item["assets"][n]["href"] for n in sorted(chosen)]
def read_rows(urls, start, end):
"""{time: row} over [start, end); a later file (recent, now) completes an earlier one."""
rows = {}
for url in urls:
text = fetch(url).decode("latin-1")
for row in csv.DictReader(io.StringIO(text), delimiter=";"):
time = datetime.strptime(row["reference_timestamp"], "%d.%m.%Y %H:%M").replace(tzinfo=timezone.utc)
if start <= time < end:
rows.setdefault(time, row)
return rows
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("place", help='a Swiss place name, or "lat,lon" (WGS84)')
parser.add_argument("start", type=parse_time, help="YYYY-MM-DD[THH:MM], UTC, included")
parser.add_argument("end", type=parse_time, help="YYYY-MM-DD[THH:MM], UTC, excluded")
parser.add_argument("--out", help="the CSV file (stdout by default)")
args = parser.parse_args()
if args.end <= args.start:
sys.exit("the end must be after the start")
if args.start >= datetime.now(timezone.utc):
sys.exit("the range must be in the past")
lat, lon, label = locate(args.place)
station = nearest_station(lat, lon)
abbr = station["station_abbr"]
print(f"{label} ({lat:.4f}, {lon:.4f}) -> station {abbr} {station['station_name']}, "
f"{station['distance_km']:.1f} km, {station['station_height_masl']} m", file=sys.stderr)
rows = read_rows(files_for(abbr, args.start, args.end), args.start, args.end)
out = open(args.out, "w", newline="", encoding="utf-8") if args.out else sys.stdout
writer = csv.writer(out)
writer.writerow(["time_utc", "station", *PARAMETERS.values()])
for time in sorted(rows):
row = rows[time]
writer.writerow([time.strftime("%Y-%m-%dT%H:%MZ"), abbr, *(row.get(p, "") for p in PARAMETERS)])
if args.out:
out.close()
print(f"{len(rows)} hours", file=sys.stderr)
if __name__ == "__main__":
main()