Skip to content
Open
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
6 changes: 4 additions & 2 deletions src/pendulum/date.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,13 +550,15 @@ def nth_of(self, unit: str, nth: int, day_of_week: WeekDay) -> Self:
Supported units are month, quarter and year.

:param unit: The unit to use
:param nth: The occurrence to use
:param nth: The occurrence to use, starting at 1
:param day_of_week: The day of week to set to.
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError(f'Invalid unit "{unit}" for first_of()')

dt = cast("Self", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
dt = None
if nth > 0:
dt = cast("Self", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
if not dt:
raise PendulumException(
f"Unable to find occurrence {nth}"
Expand Down
5 changes: 4 additions & 1 deletion src/pendulum/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,11 +1005,14 @@ def nth_of(self, unit: str, nth: int, day_of_week: WeekDay) -> Self:
to indicate the desired day_of_week, ex. DateTime.MONDAY.

Supported units are month, quarter and year.
Occurrences start at 1.
"""
if unit not in ["month", "quarter", "year"]:
raise ValueError(f'Invalid unit "{unit}" for first_of()')

dt = cast("Self | None", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
dt = None
if nth > 0:
dt = cast("Self | None", getattr(self, f"_nth_of_{unit}")(nth, day_of_week))
if not dt:
raise PendulumException(
f"Unable to find occurrence {nth}"
Expand Down
10 changes: 10 additions & 0 deletions tests/date/test_day_of_week_modifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,16 @@ def test_nth_of_month_outside_scope():
d.nth_of("month", 6, pendulum.MONDAY)


@pytest.mark.parametrize("date_type", [pendulum.Date, pendulum.DateTime])
@pytest.mark.parametrize("unit", ["month", "quarter", "year"])
@pytest.mark.parametrize("nth", [0, -1, -4])
def test_nth_of_nonpositive_occurrence(date_type, unit, nth):
d = date_type(2024, 5, 15)

with pytest.raises(PendulumException):
d.nth_of(unit, nth, pendulum.FRIDAY)


def test_nth_of_month_outside_year():
d = pendulum.date(1975, 12, 5)

Expand Down