Find the difference between two dates (excluding weekends) in Python?

Same problem Determine the difference between two dates (excluding weekend days) , but this is for javascript. How to do this in Python?

+5
source share
3 answers

Try with scikits.timeseries :

import scikits.timeseries as ts
import datetime

a = datetime.datetime(2011,8,1)
b = datetime.datetime(2011,8,29)

diff_business_days = ts.Date('B', b) - ts.Date('B', a)
# returns 20

or dateutil :

import datetime
from dateutil import rrule

a = datetime.datetime(2011,8,1)
b = datetime.datetime(2011,8,29)

diff_business_days = len(list(rrule.rrule(rrule.DAILY,
                                          dtstart=a,
                                          until=b - datetime.timedelta(days=1),
                                          byweekday=(rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR))))

scikits.timeseries looks stripped: http://pytseries.sourceforge.net/

With pandas, instead, someone can do:

import pandas as pd

a = datetime.datetime(2015, 10, 1)
b = datetime.datetime(2015, 10, 29)

diff_calendar_days = pd.date_range(a, b).size
diff_business_days = pd.bdate_range(a, b).size
+7
source

Here's a solution to the O (1) complexity class, which uses only the Python built-in libraries.

.

#
# by default, the last date is not inclusive
#
def workdaycount(first, second, inc = 0):
   if first == second:
      return 0
   import math
   if first > second:
      first, second = second, first
   if inc:
      from datetime import timedelta
      second += timedelta(days=1)
   interval = (second - first).days
   weekspan = int(math.ceil(interval / 7.0))
   if interval % 7 == 0:
      return interval - weekspan * 2
   else:
      wdf = first.weekday()
      if (wdf < 6) and ((interval + wdf) // 7 == weekspan):
         modifier = 0
      elif (wdf == 6) or ((interval + wdf + 1) // 7 == weekspan):
         modifier = 1
      else:
         modifier = 2
      return interval - (2 * weekspan - modifier)

#
# sample usage
#
print workdaycount(date(2011, 8, 15), date(2011, 8, 22)) # returns 5
print workdaycount(date(2011, 8, 15), date(2011, 8, 22), 1) # last date inclusive, returns 6
+2

Not sure if this is the best solution, but it works for me:

from datetime import datetime, timedelta

startDate = datetime(2011, 7, 7)
endDate = datetime(2011, 10, 7)
dayDelta = timedelta(days=1)
diff = 0
while startDate != endDate:
    if startDate.weekday() not in [5,6]:
        diff += 1
    startDate += dayDelta
+1
source

All Articles