python 计算两个日期之间的天数差、周数差、月数差、年数差
1、天数差(datetime、parse、rrule) import datetime as dtfrom dateutil import parserfrom dateutil import rrule######################################## date形式天数差d1 = '2019-07-26'd2 = '2020-08-01'######## 法1# (1)先将字符串-->时间格式datedate1 = 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######## 法2Days = (parser.parse(d2) - parser.parse(d1)).days######## 法3Days = 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) ######## 法1Days = (date2 - date1).days######## 法2Days = (parser.parse(d2) - parser.parse(d1)).days######## 法3Days = 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()