Skip to content

Commit 5be50a5

Browse files
authored
Input handling improvements for get_nth_working_day (#2770)
1 parent e3b6e26 commit 5be50a5

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

holidays/holiday_base.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1116,6 +1116,7 @@ def get_nth_working_day(self, key: DateLike, n: int) -> date:
11161116
"""Find the n-th working day from a given date.
11171117
11181118
Moves forward if n is positive, or backward if n is negative.
1119+
If n is 0, returns the given date if it is a working day; otherwise the next working day.
11191120
11201121
Args:
11211122
key:
@@ -1128,10 +1129,11 @@ def get_nth_working_day(self, key: DateLike, n: int) -> date:
11281129
Returns:
11291130
The calculated working day after shifting by n working days.
11301131
"""
1131-
direction = +1 if n > 0 else -1
1132+
direction = +1 if n >= 0 else -1
11321133
dt = self.__keytransform__(key)
1133-
for _ in range(abs(n)):
1134-
dt = _timedelta(dt, direction)
1134+
for _ in range(abs(n) or 1):
1135+
if n:
1136+
dt = _timedelta(dt, direction)
11351137
while not self.is_working_day(dt):
11361138
dt = _timedelta(dt, direction)
11371139
return dt

tests/test_holiday_base.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1262,6 +1262,10 @@ def test_get_nth_working_day(self):
12621262
self.assertEqual(self.hb.get_nth_working_day("2024-05-10", -7), date(2024, 4, 29))
12631263
self.assertEqual(self.hb.get_nth_working_day("2024-05-10", -5), date(2024, 5, 3))
12641264

1265+
self.assertEqual(self.hb.get_nth_working_day("2024-07-27", 0), date(2024, 7, 29))
1266+
self.assertEqual(self.hb.get_nth_working_day("2024-07-27", 1), date(2024, 7, 29))
1267+
self.assertEqual(self.hb.get_nth_working_day("2024-07-29", 0), date(2024, 7, 29))
1268+
12651269
def test_get_working_days_count(self):
12661270
self.assertEqual(self.hb.get_working_days_count("2024-01-03", "2024-01-23"), 15)
12671271
self.assertEqual(self.hb.get_working_days_count("2024-01-23", "2024-01-03"), 15)

0 commit comments

Comments
 (0)