Last active
May 10, 2025 17:17
-
-
Save StefRe/18032bbadd4ed43934223b9601a39bb5 to your computer and use it in GitHub Desktop.
Get number of business days between two dates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import holidays | |
import numpy as np | |
import pandas as pd | |
start = '2025-04-30' | |
end = '2025-05-06' | |
# holidays (end date is included) | |
h = holidays.country_holidays('DE', subdiv='SN') | |
print(h.get_working_days_count(start, end)- h.is_working_day(end)) | |
# numpy + holidays | |
cal = np.busdaycalendar(holidays=list(h.keys())) | |
print(np.busday_count(start, end, busdaycal=cal)) | |
# pandas usage example | |
df = pd.DataFrame({'From': pd.date_range('2025-04-01', periods=7, freq='4D', normalize=True), | |
'To': pd.date_range('2025-03-30', periods=7, freq='6D', normalize=True)}) | |
df['BDays'] = np.busday_count(df.From.to_numpy('datetime64[D]'), df.To.to_numpy('datetime64[D]'), busdaycal=cal) | |
df['Dates'] = df.apply(lambda x: ', '.join(pd.bdate_range(x.From, x.To, freq='C', inclusive='left', holidays=list(h.keys())).strftime('%a %-d.%-m.')), axis=1) | |
print(df.to_string(index=False, formatters={'Dates': lambda _: f"{_:{df.Dates.str.len().max()}s}"})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: