import datetime # 計算兩個日期之間的工做日數,非天數. class workDays(): def __init__(self, start_date, end_date, days_off=None): """days_off:休息日,默認週六日, 以0(星期一)開始,到6(星期天)結束, 傳入tupple 沒有包含法定節假日, """ self.start_date = start_date self.end_date = end_date self.days_off = days_off if self.start_date > self.end_date: self.start_date,self.end_date = self.end_date, self.start_date if days_off is None: self.days_off = 5,6 # 每週工做日列表 self.days_work = [x for x in range(7) if x not in self.days_off] def workDays(self): """實現工做日的 iter, 從start_date 到 end_date , 若是在工做日內,yield 日期 """ # 還沒排除法定節假日 tag_date = self.start_date while True: if tag_date > self.end_date: break if tag_date.weekday() in self.days_work: yield tag_date tag_date += datetime.timedelta(days=1) def daysCount(self): """工做日統計,返回數字""" return len(list(self.workDays())) def weeksCount(self, day_start=0): """統計全部跨越的週數,返回數字 默認周從星期一開始計算 """ day_nextweek = self.start_date while True: if day_nextweek.weekday() == day_start: break day_nextweek += datetime.timedelta(days=1) # 區間在一週內 if day_nextweek > self.end_date: return 1 weeks = ((self.end_date - day_nextweek).days + 1)/7 weeks = int(weeks) if ((self.end_date - day_nextweek).days + 1)%7: weeks += 1 if self.start_date < day_nextweek: weeks += 1 return weeks
測試:python
a=datetime.date(2014,5,15) b=datetime.date(2014,5,13) work = workDays(a,b) for day in work.workDays(): print day,"星期",day.weekday()+1 print "總天數:", work.daysCount() print "總週數:", work.weeksCount(day_start=6)
結果:測試
2014-05-13 星期 2 2014-05-14 星期 3 2014-05-15 星期 4 總天數: 3 總週數: 1