Skip to content

add is_business_day method to date #580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
28 changes: 27 additions & 1 deletion pendulum/date.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@


class Date(FormattableMixin, date):

# Names of days of the week
_days = {
SUNDAY: "Sunday",
Expand Down Expand Up @@ -217,6 +216,33 @@ def is_anniversary(self, dt=None):
# the old name can be completely replaced with the new in one of the future versions
is_birthday = is_anniversary

def is_business_day(self, holidays: [list, tuple] = None) -> bool:
"""
Check if the date is a business day (not a weekend), including checking against an optional list of holidays

:param holidays: list or tuple containing Date or DateTime objects to be considered holidays
:type holidays: list, tuple

:rtype: bool
True if the date is a business day, otherwise false
"""

# check if this date is a weekend
if self.day_of_week == SATURDAY \
or self.day_of_week == SUNDAY:
return False

# check if this date falls on a holiday
if holidays is not None:
# TODO: prefilter the holiday list by year (test for speed)
for holiday in holidays:
if self.is_same_day(holiday):
return False

return False

return True

# ADDITIONS AND SUBSTRACTIONS

def add(self, years=0, months=0, weeks=0, days=0):
Expand Down
11 changes: 11 additions & 0 deletions tests/date/test_comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,3 +243,14 @@ def test_comparison_to_unsupported():

assert not dt1 == "test"
assert dt1 not in ["test"]


def test_is_business_day():
dt1 = pendulum.Date(2021, 11, 13) # weekend
dt2 = pendulum.Date(2021, 11, 15) # not weekend

holidays = [pendulum.Date(2020, 11, 15)]

assert not dt1.is_business_day()
assert dt2.is_business_day()
assert not dt2.is_business_day(holidays=holidays)