Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions plann/timespec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
82 changes: 82 additions & 0 deletions tests/test_timespec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading