Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find day difference between two datetimes (excluding weekend days) in Python? [duplicate]

The same problem to Find day difference between two dates (excluding weekend days) but it is for javascript. How to do that in Python?

like image 640
Drake Guan Avatar asked Aug 29 '11 07:08

Drake Guan


3 Answers

Try it 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 with 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 look depricated : 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
like image 99
eumiro Avatar answered Nov 02 '22 23:11

eumiro


Not sure that this is the best one 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
like image 40
Artsiom Rudzenka Avatar answered Nov 02 '22 23:11

Artsiom Rudzenka


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

It has constant performance regardless of time interval length and doesn't care about argument order.

#
# 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
like image 33
Saul Avatar answered Nov 03 '22 01:11

Saul