Skip to content

Instantly share code, notes, and snippets.

@StefRe
Last active May 10, 2025 17:17
Show Gist options
  • Save StefRe/18032bbadd4ed43934223b9601a39bb5 to your computer and use it in GitHub Desktop.
Save StefRe/18032bbadd4ed43934223b9601a39bb5 to your computer and use it in GitHub Desktop.
Get number of business days between two dates
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}"}))
@StefRe
Copy link
Author

StefRe commented May 10, 2025

output:

3
3
      From         To  BDays                                                 Dates
2025-04-01 2025-03-30     -2                                                      
2025-04-05 2025-04-05      0                                                      
2025-04-09 2025-04-11      2 Wed 9.4., Thu 10.4.                                  
2025-04-13 2025-04-17      3 Mon 14.4., Tue 15.4., Wed 16.4.                      
2025-04-17 2025-04-23      2 Thu 17.4., Tue 22.4.                                 
2025-04-21 2025-04-29      5 Tue 22.4., Wed 23.4., Thu 24.4., Fri 25.4., Mon 28.4.
2025-04-25 2025-05-05      5 Fri 25.4., Mon 28.4., Tue 29.4., Wed 30.4., Fri 2.5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment