python 計算兩個日期之間的天數差(datetime、parse、rrule)、秒數差、週數差、月數差、年數差

2020-09-26 09:00:10

python 計算兩個日期之間的天數差、週數差、月數差、年數差

1、天數差(datetime、parse、rrule)

import datetime as dt
from dateutil import parser
from dateutil import rrule
######################################## date形式天數差
d1 = '2019-07-26'
d2 = '2020-08-01'
######## 法1
# (1)先將字串-->時間格式date
date1 = dt.datetime.strptime(d1, "%Y-%m-%d").date()  ##datetime.date(2018, 1, 6)
date2 = dt.datetime.strptime(d2, "%Y-%m-%d").date()  ##datetime.date(2018, 1, 9)
# (2)計算兩個日期date的天數差
Days = (date2 - date1).days
######## 法2
Days = (parser.parse(d2) - parser.parse(d1)).days
######## 法3
Days = rrule.rrule(rrule.DAILY, dtstart = date1, until = date2).count()

######################################## datetime形式天數差
date1 = dt.datetime(2019, 7, 26, 15, 35, 10)  
date2 = dt.datetime(2020, 8, 1, 18, 30, 20) 
######## 法1
Days = (date2 - date1).days
######## 法2
Days = (parser.parse(d2) - parser.parse(d1)).days
######## 法3
Days = rrule.rrule(rrule.DAILY, dtstart = date1, until = date2).count() 

2、秒數差(seconds、microseconds)

# 秒數差 
Seconds = (date2 - date1).seconds  
# 毫秒數
Microseconds = (date2 - date1).microseconds  

3、週數差(rrule)

Weeks = rrule.rrule(rrule.WEEKLY, dtstart = date1, until = date2).count() 

4、月數差(rrule)

Months = rrule.rrule(rrule.MONTHLY, dtstart = date1, until = date2).count()  

5、年數差

Years = rrule.rrule(rrule.YEARLY, dtstart = date1, until = date2).count()