开发者

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

开发者 https://www.devze.com 2023-03-31 15:57 出处:网络
This question already has answers here: Number of days between 2 dates, excluding weekends (22 answers)
This question already has answers here: Number of days between 2 dates, excluding weekends (22 answers) Closed 7 years ago.

The same problem 开发者_开发知识库to Find day difference between two dates (excluding weekend days) but it is for javascript. How to do that in Python?


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消