Skip to content

Commit

Permalink
feat: support filter with weekends for get_workdays (#104)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dragon-GCS authored Jul 3, 2023
1 parent 51c0629 commit 13de4e3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
8 changes: 6 additions & 2 deletions chinese_calendar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,16 +129,20 @@ def get_holidays(start, end, include_weekends=True):
return list(filter(lambda x: x in holidays, get_dates(start, end)))


def get_workdays(start, end):
def get_workdays(start, end, include_weekends=True):
"""
get workdays between start date and end date. (includes start date and end date)
:type start: datetime.date | datetime.datetime
:type end: datetime.date | datetime.datetime
:type include_weekends: bool
:param include_weekends: False for excluding Saturdays and Sundays
:rtype: list[datetime.date]
"""
start, end = _validate_date(start, end)
return list(filter(is_workday, get_dates(start, end)))
if include_weekends:
return list(filter(is_workday, get_dates(start, end)))
return list(filter(lambda x: is_workday(x) and x.weekday() < 5, get_dates(start, end)))


def find_workday(delta_days=0, date=None):
Expand Down
21 changes: 15 additions & 6 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,25 @@ def test_get_dates(self):

def test_get_workdays_holidays(self):
cases = [
((2018, 2, 1), (2018, 1, 1), 0, 0, 0),
((2018, 1, 1), (2018, 1, 1), 1, 1, 0),
((2018, 1, 1), (2018, 1, 7), 3, 1, 4),
((2018, 1, 1), (2018, 2, 1), 9, 1, 23),
((2018, 2, 1), (2018, 1, 1), 0, 0, 0, 0),
((2018, 1, 1), (2018, 1, 1), 1, 1, 0, 0),
((2018, 1, 1), (2018, 1, 7), 3, 1, 4, 4),
((2018, 1, 1), (2018, 2, 1), 9, 1, 23, 23),
((2018, 2, 1), (2018, 3, 1), 11, 7, 18, 16),
]
for start, end, include_weekends, exclude_weekends, workdays in cases:
for (start, end, include_weekends, exclude_weekends, workdays,
workdays_exclude_weekends) in cases:
start, end = datetime.date(*start), datetime.date(*end)
self.assertEqual(include_weekends, len(chinese_calendar.get_holidays(start, end)))
self.assertEqual(exclude_weekends, len(chinese_calendar.get_holidays(start, end, include_weekends=False)))
self.assertEqual(
exclude_weekends,
len(chinese_calendar.get_holidays(start, end, include_weekends=False))
)
self.assertEqual(workdays, len(chinese_calendar.get_workdays(start, end)))
self.assertEqual(
workdays_exclude_weekends,
len(chinese_calendar.get_workdays(start, end, include_weekends=False))
)

def test_find_workday(self):
dates = [
Expand Down

0 comments on commit 13de4e3

Please # to comment.