From 252a100adcd82e07223bd0ce1ec62caf6145d1ad Mon Sep 17 00:00:00 2001 From: Tobias Brox Date: Tue, 24 Nov 2026 07:22:38 +0100 Subject: [PATCH] fix: give parsed timestamps a stdlib tzinfo dateparser returns pytz zones when a timezone is configured, and its own pytz look-alike StaticTzInfo for an explicit UTC offset. recurring_ical_events took StaticTzInfo for pytz and crashed calling normalize() on it, so `plann select --start 2026-11-21T05:00+01:00` failed on recurring events. parse_dt now swaps such zones for a zoneinfo zone or a fixed offset, keeping the wall clock. https://github.com/niccokunzmann/python-recurring-ical-events/issues/311 Prompts: > Look into > https://github.com/niccokunzmann/python-recurring-ical-events/issues/311#issuecomment-7112994959 > - am I using the wrong libraries for handling timezones in plann? > This sounds like an upstream problem with dateparser? But yes, please > implement [converting dateparser's tzinfo to zoneinfo or a > fixed offset in parse_dt]. (...) Assisted-By: Claude Opus 5.5 Reviewed-by: Tobias Brox --- CHANGELOG.md | 1 + plann/timespec.py | 26 ++++++++++++++ tests/test_timespec.py | 82 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75691ca..35c1994 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h ### Fixed +* A timestamp with an explicit UTC offset, like `plann select --event --start 2026-11-21T05:00+01:00`, crashed when expanding recurring events with `AttributeError: 'StaticTzInfo' object has no attribute 'normalize'`. https://github.com/niccokunzmann/python-recurring-ical-events/issues/311 * `plann select ... edit --set-dtend=...` on an event crashed with `TypeError: CalendarObjectResource.set_end() got an unexpected keyword argument 'check_dependent'`, so an event could not be given a new end time. It now moves the event, keeping its duration. `--set-dtend` on a task, `--set-due` on an event and either on a journal crashed too; they now give an error saying which one the item has. * The `plann agenda --help` text now lists two runnable `plann select` commands giving the same events and tasks as `agenda`. In the task one, the `--sort-key '{PRIORITY:?0}'` template had no effect and `list --bottom-up` stood where `select --skip-parents` belongs, and the event one lacked the sort keys. It also pointed to a nonexistent USAGE.md instead of USER_GUIDE.md. * `plann add -l LINE event` dropped the extra iCalendar lines; they are now added to the event, as they were to tasks and journals. diff --git a/plann/timespec.py b/plann/timespec.py index 2e5dd24..dbcdf87 100644 --- a/plann/timespec.py +++ b/plann/timespec.py @@ -89,6 +89,31 @@ def _ensure_ts(dt): return dt return datetime.datetime(dt.year, dt.month, dt.day, tzinfo=tz.implicit_timezone).astimezone(tz.implicit_timezone) +def _stdlib_tz(dt): + """Swap the tzinfo dateparser returns - a pytz zone, or its own + pytz look-alike StaticTzInfo for an explicit offset - for a + zoneinfo zone or a fixed offset. icalendar and recurring_ical_events + only support zoneinfo (and legacy pytz). + + The wall clock is kept, not the instant: pytz puts a time in a DST + gap at an instant that reads an hour later in zoneinfo, which would + turn a date-only input into a 01:00 timestamp where the clocks go + forward at midnight. An ambiguous time keeps the offset pytz chose.""" + tzinfo = dt.tzinfo + if tzinfo is None or isinstance(tzinfo, (zoneinfo.ZoneInfo, datetime.timezone)): + return dt + zone = getattr(tzinfo, 'zone', None) + if zone: + try: + ret = dt.replace(tzinfo=zoneinfo.ZoneInfo(zone)) + except (zoneinfo.ZoneInfoNotFoundError, ValueError): + pass + else: + if ret.utcoffset() != dt.utcoffset() and ret.replace(fold=1).utcoffset() == dt.utcoffset(): + ret = ret.replace(fold=1) + return ret + return dt.replace(tzinfo=datetime.timezone(dt.utcoffset())) + def parse_dt(input, return_type=None, for_storage=False): """ Convenience-method, it is very liberal in what it accepts as input: @@ -136,6 +161,7 @@ def _parse_dt(input, return_type=None): ret = dateparser.parse(input, settings=settings) if ret is None: raise ValueError(f"Could not parse datetime string: {input!r}") + ret = _stdlib_tz(ret) if return_type is datetime.datetime: return _ensure_ts(ret) elif return_type is datetime.date: diff --git a/tests/test_timespec.py b/tests/test_timespec.py index f9fd686..154698f 100644 --- a/tests/test_timespec.py +++ b/tests/test_timespec.py @@ -291,3 +291,85 @@ def test_ensure_ts(): assert(_ensure_ts(now) == implicitnow) assert(_ensure_ts(utcnow) == utcnow) assert(_ensure_ts(implicitnow) == implicitnow) + + +class TestTzinfoFromDateparser: + """dateparser hands out pytz zones and its own pytz look-alike + ``StaticTzInfo``; icalendar and recurring_ical_events only support + zoneinfo (and pytz as legacy), so parse_dt must only return stdlib + tzinfo objects - see + https://github.com/niccokunzmann/python-recurring-ical-events/issues/311""" + + @staticmethod + def _assert_stdlib_tz(dt): + assert isinstance(dt.tzinfo, (ZoneInfo, timezone)), type(dt.tzinfo) + + @pytest.mark.parametrize("input,offset", [ + ("2026-11-21T05:00+01:00", timedelta(hours=1)), + ("2026-11-21T05:00-05:00", timedelta(hours=-5)), + ("2026-11-21T05:00+05:30", timedelta(hours=5, minutes=30)), + ("2026-11-21 05:00 Z", timedelta(0)), + ("2026-11-21 05:00 EST", timedelta(hours=-5)), + ]) + def test_explicit_offset(self, input, offset): + result = parse_dt(input) + self._assert_stdlib_tz(result) + assert result.utcoffset() == offset + assert result.replace(tzinfo=None) == datetime(2026, 11, 21, 5, 0) + + @pytest.mark.parametrize("input,offset", [ + ("2026-07-01 14:00", timedelta(hours=2)), + ("2026-12-01 14:00", timedelta(hours=1)), + ]) + def test_implicit_timezone(self, input, offset): + """With a configured timezone dateparser returns a pytz zone; + the converted value keeps both the wall clock and the offset""" + tz.implicit_timezone = "Europe/Oslo" + result = parse_dt(input) + assert result.tzinfo == OSLO + assert result.utcoffset() == offset + assert result.hour == 14 + + @pytest.mark.parametrize("zone,input,expected", [ + ## the clocks go forward at midnight there: a date stays a date + ("America/Santiago", "2026-09-06", date(2026, 9, 6)), + ("America/Havana", "2026-03-08", date(2026, 3, 8)), + ]) + def test_date_in_midnight_dst_gap(self, zone, input, expected): + tz.implicit_timezone = zone + assert parse_dt(input) == expected + + @pytest.mark.parametrize("input,offset", [ + ("2026-03-29 02:30", timedelta(hours=1)), # in the spring-forward gap + ("2026-10-25 02:30", timedelta(hours=1)), # ambiguous; dateparser takes standard time + ]) + def test_dst_transition_keeps_wall_clock(self, input, offset): + """The time typed is the time shown, with the offset dateparser chose""" + tz.implicit_timezone = "Europe/Oslo" + result = parse_dt(input) + assert result.tzinfo == OSLO + assert (result.hour, result.minute) == (2, 30) + assert result.utcoffset() == offset + + def test_natural_language_with_implicit_timezone(self): + tz.implicit_timezone = "Europe/Oslo" + self._assert_stdlib_tz(parse_dt("tomorrow 14:00")) + + def test_timespec(self): + tz.implicit_timezone = "Europe/Oslo" + for ts in parse_timespec("2026-11-21T05:00+01:00 2026-11-21T07:00+01:00"): + self._assert_stdlib_tz(ts) + + def test_recurring_ical_events_between(self): + """The crash reported upstream: between() on a recurring event + with a parsed explicit-offset timestamp""" + import icalendar + import recurring_ical_events + cal = icalendar.Calendar.from_ical( + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:test\r\n" + "BEGIN:VEVENT\r\nUID:daily@example.com\r\n" + "DTSTART:20261101T050000Z\r\nDURATION:PT1H\r\nRRULE:FREQ=DAILY\r\n" + "END:VEVENT\r\nEND:VCALENDAR\r\n") + start = parse_dt("2026-11-21T05:00+01:00") + end = parse_dt("2026-11-21T07:00+01:00") + assert len(recurring_ical_events.of(cal).between(start, end)) == 1