Skip to content

Commit 554227c

Browse files
committed
Reject nonpositive weekday occurrences
1 parent e06dace commit 554227c

3 files changed

Lines changed: 18 additions & 3 deletions

File tree

‎src/pendulum/date.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -550,13 +550,15 @@ def nth_of(self, unit: str, nth: int, day_of_week: WeekDay) -> Self:
550550
Supported units are month, quarter and year.
551551
552552
:param unit: The unit to use
553-
:param nth: The occurrence to use
553+
:param nth: The occurrence to use, starting at 1
554554
:param day_of_week: The day of week to set to.
555555
"""
556556
if unit not in ["month", "quarter", "year"]:
557557
raise ValueError(f'Invalid unit "{unit}" for first_of()')
558558

559-
dt = cast("Self", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
559+
dt = None
560+
if nth > 0:
561+
dt = cast("Self", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
560562
if not dt:
561563
raise PendulumException(
562564
f"Unable to find occurrence {nth}"

‎src/pendulum/datetime.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1005,11 +1005,14 @@ def nth_of(self, unit: str, nth: int, day_of_week: WeekDay) -> Self:
10051005
to indicate the desired day_of_week, ex. DateTime.MONDAY.
10061006
10071007
Supported units are month, quarter and year.
1008+
Occurrences start at 1.
10081009
"""
10091010
if unit not in ["month", "quarter", "year"]:
10101011
raise ValueError(f'Invalid unit "{unit}" for first_of()')
10111012

1012-
dt = cast("Self | None", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
1013+
dt = None
1014+
if nth > 0:
1015+
dt = cast("Self | None", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
10131016
if not dt:
10141017
raise PendulumException(
10151018
f"Unable to find occurrence {nth}"

‎tests/date/test_day_of_week_modifiers.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,16 @@ def test_nth_of_month_outside_scope():
196196
d.nth_of("month", 6, pendulum.MONDAY)
197197

198198

199+
@pytest.mark.parametrize("date_type", [pendulum.Date, pendulum.DateTime])
200+
@pytest.mark.parametrize("unit", ["month", "quarter", "year"])
201+
@pytest.mark.parametrize("nth", [0, -1, -4])
202+
def test_nth_of_nonpositive_occurrence(date_type, unit, nth):
203+
d = date_type(2024, 5, 15)
204+
205+
with pytest.raises(PendulumException):
206+
d.nth_of(unit, nth, pendulum.FRIDAY)
207+
208+
199209
def test_nth_of_month_outside_year():
200210
d = pendulum.date(1975, 12, 5)
201211

0 commit comments

Comments
 (0)