#!/usr/bin/env python3 """ Calendar Cleanup — remove old events from an exported .ics calendar file. Two modes: 1. before (default): delete events BEFORE a cutoff date Usage: python3 ics_filter.py calendar.ics 2026-11-10 2. range: delete events STARTING within a date range (boundaries inclusive) Usage: python3 ics_filter.py calendar.ics --from 2023-01-01 --to 2023-12-31 Creates, next to where you run it: -cleaned.ics the cleaned calendar — import this one -removed-events.ics what was removed — only for checking Recurring events are kept unless the whole series ended before the cutoff / inside the range. Endless recurrences are always kept — their future occurrences matter. Only the Python standard library is used. The same logic runs in the browser (filter.js); keep both in sync. """ import argparse import math import re from datetime import date, datetime, timedelta, timezone from pathlib import Path def _unfold(lines): """Join continuation lines (starting with space/tab) into whole lines.""" out = [] for line in lines: line = line.rstrip("\r\n") if line[:1] in (" ", "\t") and out: out[-1] += line[1:] else: out.append(line) return out def _split_events(unfolded): """Split into header / events / footer (only at top level).""" header, events, footer = [], [], [] target = header depth = 0 ev = None for line in unfolded: upper = line.upper() if upper.startswith("BEGIN:VEVENT") and depth == 0: depth = 1 ev = [line] # BEGIN:VEVENT target = None continue if depth > 0: ev.append(line) # ALL lines, including END:VEVENT if upper.startswith("BEGIN:"): depth += 1 elif upper.startswith("END:"): depth -= 1 if depth == 0: events.append(ev) ev = None target = footer continue target.append(line) return header, events, footer def _parse_props(event_lines): """Top-level properties of a VEVENT (nested VALARM etc. are skipped).""" props = {} depth = 0 for line in event_lines[1:-1]: upper = line.upper() if upper.startswith("BEGIN:"): depth += 1 continue if upper.startswith("END:"): depth -= 1 continue if depth > 0 or ":" not in line: continue name_part, _, value = line.partition(":") name = name_part.split(";", 1)[0].upper() props.setdefault(name, []).append(value) return props # ---------- date helpers (dates are 'YYYYMMDD' strings; they compare correctly) ---------- def _parse_ics_value(value): """Parse 'YYYYMMDD' or 'YYYYMMDDTHHMMSS[Z]'. Returns (date, time or None) or None. UTC times ('...Z') are converted to this computer's local time zone, so an event at 00:30 local time counts as that day even though it is 23:30 the day before in UTC. This only affects which day an event is counted on; the file is never changed. """ m = re.fullmatch(r"(\d{8})(?:T(\d{6})(Z?))?", value.strip()) if not m: return None try: _to_date(m.group(1)) # reject impossible dates like 20230231 except ValueError: return None if m.group(2) and m.group(3): try: utc = datetime.strptime(m.group(1) + m.group(2), "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc) local = utc.astimezone() return local.strftime("%Y%m%d"), local.strftime("%H%M%S") except (ValueError, OverflowError, OSError): pass return m.group(1), m.group(2) def _to_date(ymd): return date(int(ymd[:4]), int(ymd[4:6]), int(ymd[6:8])) def _add_days(ymd, n): try: return (_to_date(ymd) + timedelta(days=n)).strftime("%Y%m%d") except OverflowError: return "99991231" if n > 0 else "00010101" def _add_months(ymd, n): """Add months; the day is capped at 28 so it never overflows into the next month.""" total = int(ymd[:4]) * 12 + int(ymd[4:6]) - 1 + n y, m = divmod(total, 12) return f"{y:04d}{m + 1:02d}{min(int(ymd[6:8]), 28):02d}" def _days_between(a, b): return (_to_date(b) - _to_date(a)).days def _first_value(props, key): for value in props.get(key, []): p = _parse_ics_value(value) if p: return p return None # ---------- event dates ---------- def _event_start(props): """Event start date as YYYYMMDD string, or None.""" s = _first_value(props, "DTSTART") return s[0] if s else None def _event_end(props): """Last day the event actually covers, as YYYYMMDD string. DTEND is exclusive: an all-day event on Nov 9 has DTEND = Nov 10, and an event ending exactly at midnight does not touch the following day. """ start = _event_start(props) e = _first_value(props, "DTEND") if e: end, time = e if time is None or time == "000000": end = _add_days(end, -1) if start and end < start: end = start return end return start # ---------- recurrence ---------- def _parse_rrule(value): r = {} for part in value.split(";"): key, sep, val = part.partition("=") if sep and key: r[key.upper()] = val.upper() return r def _is_sparse(r, start): """Rules that skip whole periods (e.g. 'monthly on the 31st', 'every Feb 29', '5th Friday'), so COUNT occurrences can stretch far beyond COUNT periods.""" if r.get("BYSETPOS") or r.get("BYYEARDAY") or r.get("BYWEEKNO"): return True if r.get("BYMONTH") and r.get("FREQ") != "YEARLY": return True if r.get("BYMONTHDAY"): for d in r["BYMONTHDAY"].split(","): try: if not 1 <= int(d) <= 28: return True except ValueError: return True if r.get("BYDAY") and any(re.match(r"^[+-]?5", d) for d in r["BYDAY"].split(",")): return True if (r.get("FREQ") in ("MONTHLY", "YEARLY") and not r.get("BYDAY") and not r.get("BYMONTHDAY") and int(start[6:8]) > 28): return True return False _SUB_DAILY_SECONDS = {"SECONDLY": 1, "MINUTELY": 60, "HOURLY": 3600} def _series_end(props): """Upper bound for the last day a recurring series covers, or None if it never ends (or we can't tell — callers treat None as 'keep').""" start = _event_start(props) end = _event_end(props) if not start or not end: return None duration = _days_between(start, end) r = _parse_rrule(props.get("RRULE", [""])[0]) if r.get("UNTIL"): u = _parse_ics_value(r["UNTIL"]) return _add_days(u[0], duration) if u else None if r.get("COUNT"): try: count = int(r["COUNT"]) interval = int(r.get("INTERVAL", "1")) or 1 except ValueError: return None if count <= 0 or _is_sparse(r, start): return None # Every period holds at least one occurrence, so the last one starts # within count * interval periods of DTSTART (one period of slack). k = count * interval freq = r.get("FREQ") if freq == "DAILY": last = _add_days(start, k) elif freq == "WEEKLY": last = _add_days(start, 7 * k) elif freq == "MONTHLY": last = _add_months(start, k) elif freq == "YEARLY": last = _add_months(start, 12 * k) elif freq in _SUB_DAILY_SECONDS: last = _add_days(start, math.ceil(k * _SUB_DAILY_SECONDS[freq] / 86400) + 1) else: return None return _add_days(last, duration) return None # endless def should_delete(props, spec): start = _event_start(props) end = _event_end(props) if end is None: return False # unknown date -> keep if "RRULE" in props: last = _series_end(props) if last is None: return False # endless / unknown -> keep (future occurrences matter) if spec["kind"] == "before": return last < spec["cutoff"] return start >= spec["from"] and last <= spec["to"] # whole series inside range if spec["kind"] == "before": return end < spec["cutoff"] s = start or end return spec["from"] <= s <= spec["to"] def _write_output(filename, header, blocks, footer): with open(filename, "w", encoding="utf-8", newline="") as f: f.write("".join(l + "\r\n" for l in header)) for block in blocks: f.write("".join(l + "\r\n" for l in block)) f.write("".join(l + "\r\n" for l in footer)) def main(): parser = argparse.ArgumentParser( description="Remove old events from an .ics calendar file.", epilog="Examples:\n" " python3 ics_filter.py cal.ics 2026-11-10\n" " python3 ics_filter.py cal.ics --from 2023-01-01 --to 2023-12-31", formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("file", help="input .ics file") parser.add_argument("cutoff", nargs="?", metavar="YYYY-MM-DD", help="delete events BEFORE this day (mode 1)") parser.add_argument("--from", dest="from_date", metavar="YYYY-MM-DD", help="range mode: delete events starting from this day (inclusive)") parser.add_argument("--to", dest="to_date", metavar="YYYY-MM-DD", help="range mode: delete events starting until this day (inclusive)") args = parser.parse_args() # resolve mode if args.from_date or args.to_date: if not (args.from_date and args.to_date): parser.error("range mode requires both --from and --to") try: f = datetime.strptime(args.from_date, "%Y-%m-%d").date() t = datetime.strptime(args.to_date, "%Y-%m-%d").date() except ValueError as e: parser.error(f"invalid date: {e}") if f > t: parser.error("--from must not be after --to") spec = {"kind": "range", "from": f.strftime("%Y%m%d"), "to": t.strftime("%Y%m%d")} desc = f"range {args.from_date} .. {args.to_date} (boundaries inclusive)" elif args.cutoff: try: d = datetime.strptime(args.cutoff, "%Y-%m-%d").date() except ValueError as e: parser.error(f"invalid cutoff date: {e}") spec = {"kind": "before", "cutoff": d.strftime("%Y%m%d")} desc = f"deleting events older than {args.cutoff}" else: parser.error("provide a cutoff date, or --from and --to for range mode") with open(args.file, encoding="utf-8-sig", errors="replace") as fh: unfolded = _unfold(fh.readlines()) header, events, footer = _split_events(unfolded) kept, dropped = [], [] for ev in events: (dropped if should_delete(_parse_props(ev), spec) else kept).append(ev) base = Path(args.file).name base = base[:-4] if base.lower().endswith(".ics") else base cleaned_name = f"{base or 'calendar'}-cleaned.ics" removed_name = f"{base or 'calendar'}-removed-events.ics" _write_output(cleaned_name, header, kept, footer) _write_output(removed_name, header, dropped, footer) print(f"Mode: {desc}") print(f"Kept: {len(kept)} events -> {cleaned_name} (import this one)") print(f"Removed: {len(dropped)} events -> {removed_name} (only for checking)") if __name__ == "__main__": main()