Python date range generator over business days

I would strong recommend using the dateutil library for such tasks. A basic (not ignoring holidays) iterator over business days then simply is:

from dateutil.rrule import DAILY, rrule, MO, TU, WE, TH, FR

def daterange(start_date, end_date):
  return rrule(DAILY, dtstart=start_date, until=end_date, byweekday=(MO,TU,WE,TH,FR))

There's a useful library called dateutil that can do this sort of thing for you. It can generate ranges of dates (or dates based on custom rules), excluding certain days, consider a week starting on a day etc... Also has a somewhat more flexible timedelta than the builtin datetime library.

Docs at http://labix.org/python-dateutil/ - and available on PyPi


Assuming startDate and endDate are datetime or date objects, you can use the weekday method to get the day of the week, then skip it if it's Saturday or Sunday. Just do:

def daterange(startDate, endDate):
    for i in xrange(int((endDate - startDate).days)):
        nextDate = startDate + timedelta(i)
        if nextDate.weekday() not in (5, 6):
            yield startDate + timedelta(i)

For holidays you will have to check manually for each holiday you want. Some holidays are defined in complex ways so this could be a bit tricky.


Python pandas has a built-in method bdate_range() with Business Days as it's default frequency. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.bdate_range.html

import pandas as pd
pd.bdate_range(start='1/25/2020', end='2/24/2020')

Tags:

Python