在Python中查找两个日期时间(不包括周末日)之间的日差异?

时间:2011-08-29 07:14:44

标签: python datetime

Find day difference between two dates (excluding weekend days)相同的问题,但它适用于javascript。如何在Python中做到这一点?

3 个答案:

答案 0 :(得分:7)

使用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

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看起来已被删除:http://pytseries.sourceforge.net/

使用pandas而不是某人可以做到:

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

答案 1 :(得分:3)

这是一个O(1)复杂性类解决方案,它只使用内置的Python库。

无论时间间隔长度如何,它都具有恒定的性能,并且不关心参数顺序。

#
# 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 :(得分:1)

不确定这是最好的解决方案,但它对我有用:

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