0

I have two dates as datetime.date objects, what is the most Pythonic way to find a number of workdays between these two dates (including starting and excluding ending date)? For example:

from datetime import date, timedelta

d1 = date(2019, 3, 1)
d2 = date(2019, 5, 6)
# The difference between d2 and d1 is 46 workdays

Writting a loop comes to my mind:

workdays = 0
for i in range((d2 - d1).days):
    if (d1 + timedelta(days=i)).isoweekday() <= 5:
        workdays += 1

However, I think there is a simpler way to solve this problem.

niekas
  • 8,187
  • 7
  • 40
  • 58

2 Answers2

5

use the numpy function busday_count:

from datetime import date
import numpy as np

d1 = date(2019, 3, 1)
d2 = date(2019, 5, 6)

days = np.busday_count( d1, d2 )
print (days)

or

from datetime import date,timedelta
d1 = date(2019, 3, 1)
d2 = date(2019, 5, 6)
daygenerator = (d1 + timedelta(x + 1) for x in range((d2 - d1).days)) # generate all days from d1 to d2
print (sum(1 for day in daygenerator if day.weekday() < 5)) 
ncica
  • 7,015
  • 1
  • 15
  • 37
2

You can try this:

It does not take holidays,.. into account:

import numpy as np
np.busday_count(d1.strftime("%Y-%m-%d"), d2.strftime("%Y-%m-%d"))
Klemen Koleša
  • 446
  • 3
  • 6