Number of days between 2 dates, excluding weekends

How can I calculate number of days between two dates excluding weekends?


I think the cleanest solution is to use the numpy function busday_count

import numpy as np
import datetime as dt

start = dt.date( 2014, 1, 1 )
end = dt.date( 2014, 1, 16 )

days = np.busday_count( start, end )

>>> from datetime import date,timedelta
>>> fromdate = date(2010,1,1)
>>> todate = date(2010,3,31)
>>> daygenerator = (fromdate + timedelta(x + 1) for x in xrange((todate - fromdate).days))
>>> sum(1 for day in daygenerator if day.weekday() < 5)
63

This creates a generator using a generator expression which will yield the list of days to get from the fromdate to todate.

We could then create a list from the generator, filtering out weekends using the weekday() function, and the size of the list gives the number of days we want. However, to save having the whole list in memory which could be a problem if the dates are a long time apart we use another generator expression which filters out weekends but returns 1 instead of each date. We can then just add all these 1s together to get the length without having to store the whole list.

Note, if fromdate == todate this calculate 0 not 1.


First import numpy as np. The function np.busday_count counts the number of valid days between two dates, excluding the day of the end date.

If end date is earlier than the begin date, the count will be negative. For more on np.busday_count read the documentation here.

import numpy as np
np.busday_count('2018-04-10', '2018-04-11')

Note that the function accepts strings, it's not necessary to instantiate datetime objects before calling the function.

Also supports specific valid days and option to add holidays as well.

import numpy as np
np.busyday_count('2019-01-21','2020-03-28',weekmask=[1,1,1,1,1,0,0],holidays=['2020-01-01'])

weekmask format = [Mon,Tue,Wed.....Sat,Sun]


The lazy way is to pip install workdays to get the python package that does exactly this.

https://pypi.python.org/pypi/workdays/