Next Waste Disposal in Stuttgart as JSON
The city of Stuttgart has a website that generates an ical link for every address in the city when waste is collected. To display on a dashboard I wanted the next dates for waste, paper and recycling collection. But the ical generated by the city is non-rfc5545 compliant and all Python libraries I tried failed to parse the file: ics, ical and ical-library.
So I had to parse the file myself. Additionally I wanted to use no dependencies, so urllib from Python is used. The code is not fault tolerant in any way and solves exactly my problem: Return the next 3 dates waste is collected for my address.
Full Code:
import datetime import json import sys from urllib import request def parse(stream): ds = {} for line in stream.split("\n"): if line.strip() == "BEGIN:VEVENT" and ds: yield ds ds = {} if line.startswith("DTSTART"): ds["date"] = str( datetime.datetime.strptime( line.split(":")[-1].split("T")[0], "%Y%m%d" ).date() ) if line.startswith("SUMMARY"): ds["summary"] = line.split(":")[-1].strip() r = request.urlopen(request.Request(sys.argv[1])) keys = ["Restmüll 02-wöchentl.", "Altpapier 03-wöchentl.", "Gelber Sack 03-wöchentl."] result = [] for item in parse(r.read().decode("utf-8")): if item.get("summary") in keys: result.append(item) del keys[keys.index(item.get("summary"))] print(json.dumps(result, indent=2, ensure_ascii=False))
Example call:
python run.py https://service.stuttgart.de/lhs-services/aws/api/ical\?street\=Rathausplatz\&streetnr\=1
Results in:
[ { "summary": "Restmüll 02-wöchentl.", "date": "2023-02-10" }, { "summary": "Altpapier 03-wöchentl.", "date": "2023-02-22" }, { "summary": "Gelber Sack 03-wöchentl.", "date": "2023-02-10" } ]