from dateutil import rrule
from datetime import datetime
from_date = datetime(2022, 1, 1)
end_date = datetime(2023, 2, 2)
diff_hour = rrule.rrule(rrule.HOURLY, dtstart=from_date, until=end_date).count() # 相差小時數
diff_day = rrule.rrule(rrule.DAILY, dtstart=from_date, until=end_date).count() # 相差天數
diff_month = rrule.rrule(rrule.MONTHLY, dtstart=from_date, until=end_date).count() # 相差月數
diff_year = rrule.rrule(rrule.YEARLY, dtstart=from_date, until=end_date).count() # 相差年數
這裡需要注意的一點是,The gaps between the same time points are all1,如下代碼:
rrule.rrule(rrule.HOURLY, dtstart=from_date, until=from_date).count() # 相差小時數: 值為1
rrule.rrule(rrule.DAILY, dtstart=from_date, until=from_date).count() # 相差小時數: 值為1
rrule.rrule(rrule.MONTHLY, dtstart=from_date, until=from_date).count() # 相差小時數: 值為1
And if in time:dtstart
>until
,則值都為0