I'm trying to create a generator function to iterate over business days (weekdays), skipping weekends (and holidays would be nice too!). So far, I only have a function that simply iterates over days:
def daterange(startDate, endDate):
for i in xrange(int((endDate - startDate).days)):
yield startDate + timedelta(i)
I'm struggling to figure out a clean, efficient, and pythonic way to make the generator skip over weekends and holidays. Thanks in advance!
Using pandas to Iterate through a range of dates We can use the date_range() function method that is available in pandas. It is used to return a fixed frequency DatetimeIndex.
Use the busday_count() function of a numpy library The busday_count() function counts the number of business days between the start date and end date, not including the day of the end dates.
import pandas from datetime import datetime, timedelta startDate = datetime(2022, 6, 1) endDate = datetime(2022, 6, 10) # Getting List of Days using pandas datesRange = pandas. date_range(startDate,endDate-timedelta(days=1),freq='d') print(datesRange);
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With