2011-08-29 129 views

回答

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看depricated:http://pytseries.sourceforge.net/

隨着熊貓,而不是一個人可以這樣做:

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

不知道這是最好的解決方案,但它爲我工作:

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 
+2

或者減去2 *(天數// 7),然後調整一週中開始和結束日期的位置,如果您希望更快一些。 – agf

2

這裏是一個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 
相關問題