Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python date range generator over business days

Tags:

python

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!

like image 419
jh314 Avatar asked Jul 18 '12 21:07

jh314


People also ask

How do you iterate over a date range in Python?

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.

How do I calculate business days between dates in Python?

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.

How do I generate all dates between two dates in Python?

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);


2 Answers

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')
like image 176
SGI Avatar answered Oct 27 '22 20:10

SGI


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.

like image 21
BrenBarn Avatar answered Oct 27 '22 20:10

BrenBarn