请你编写一个程序来计算两个日期之间隔了多少天。
日期以字符串形式给出,格式为 YYYY-MM-DD,如示例所示。
示例 1:
输入:date1 = “2019-06-29”, date2 = “2019-06-30”
输出:1
示例 2:
输入:date1 = “2020-01-15”, date2 = “2019-12-31”
输出:15
提示:
给定的日期是 1971 年到 2100 年之间的有效日期。
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
# 计算每个日期与1970-12-30的间隔,然后相减
spa1 = self.space(date1)
spa2 = self.space(date2)
return abs(spa1 - spa2)
def space(self, date):
monthday = [31,28,31,30,31,30,31,31,30,31,30,31]
year, month,day = year, month, day = int(date.split('-')[0]),int(date.split('-')[1]),int(date.split('-')[2])
# 间隔年份为[1970.year - 1],同时,加上闰年多出来的天数
days = 0
days += (year - 1970-1)*365 + (year-1-1968)//4
days += sum(monthday[:month-1])
if year%400 == 0 or (year % 4 == 0 and year % 100 !=0 ) and month > 2:
day += 1
days += day
return days