計算任意兩個日期之間的天數,週數。《python大學實用教程》例子

君子令儀發表於2020-10-17
import datetime
from dateutil import rrule
class BetDate:
    def __init__(self,start_date,stop_date):
        self.start=datetime.datetime.strptime(start_date,"%Y,%m,%d")
        self.stop=datetime.datetime.strptime(stop_date,"%Y,%m,%d")
    def days(self):
        d=self.stop - self.start
        return d.days if d.days>0  else False
    def weeks(self):
        weeks=rrule.rrule(rrule.WEEKLY,dtstart=self.start,until=self.stop)
        return weeks.count()
fir_twe=BetDate("2018,5,1","2018,5,25")
d=fir_twe.days()
w=fir_twe.weeks()

print("between 2018-5-1,2018-5-25:")
print("Day is :",d)
print("Weeks is:",w)

輸出:

between 2018-5-1,2018-5-25:
Day is : 24
Weeks is: 4

相關文章