[英]count the number of days between two dates
I am counting number of days between two dates.For first testcase output is wrong 10108 expected output 10109 In first test case 1 day is missing in output我正在计算两个日期之间的天数。对于第一个测试用例 output 是错误的 10108 预期 output 10109 在第一个测试用例中,Z78E6221F6393D1356681DBCE39 缺少 1 天
from typing import*
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
d1 = self.days(int(date1[:4]),int(date1[5:7]),int(date1[8:]))
d2 = self.days(int(date2[:4]),int(date2[5:7]),int(date2[8:]))
return abs(d2-d1)
def isLeap (self, N):
if N % 400 == 0:
return True
if N % 100 == 0:
return False
if N % 4 != 0:
return False
return True
def days(self, year,month,rem_days):
months_list = [31,28,31,30,31,30,31,31,30,31,30,31]
days_count = 0
for i in range(1971,2101):
if year > i:
if self.isLeap(i):
days_count += 366
else:
days_count += 365
else:
break
if self.isLeap(year) and month > 2:
days_count += 1
for j in range(1,month):
if month > j:
days_count += months_list[j]
return days_count + rem_days
vals = Solution()
print(vals.daysBetweenDates("2010-09-12","1983-01-08"))
print(vals.daysBetweenDates("2019-06-29", "2019-06-30"))
print(vals.daysBetweenDates("2020-01-15", "2019-12-31"))
The month starts at one, you get the number of days for each month from the wrong index (1 for January when the correct index is 0...).月份从 1 开始,您从错误的索引中获取每个月的天数(当正确的索引为 0 时,1 表示 1 月...)。 Subtract one when you look up the days for each month
查找每个月的天数时减去一个
for j in range(1, month):
days_count += months_list[j - 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.