Python计算两个日期之间的天数时,在一个特定情况下返回错误的值
我写了一个程序来计算两个日期之间的天数,除了一个例子外,它工作正常。如果我想计算两个日期之间的天数,而结束日期是在2月,则天数不正确(正好缺少三天) 例如:Python计算两个日期之间的天数时,在一个特定情况下返回错误的值,python,Python,我写了一个程序来计算两个日期之间的天数,除了一个例子外,它工作正常。如果我想计算两个日期之间的天数,而结束日期是在2月,则天数不正确(正好缺少三天) 例如: Date 1: 2012,1,1 Date 2: 2012,2,28 Program returns 55 days (should be 58) 我想闰日是有问题的,但我不明白为什么这不会导致任何其他两个日期的错误值,以及为什么正确值和我的程序值之间的差异是3天。我的代码示例应该按原样工作,可以在下面找到。任何建议都将不胜感激 days
Date 1: 2012,1,1
Date 2: 2012,2,28
Program returns 55 days (should be 58)
我想闰日是有问题的,但我不明白为什么这不会导致任何其他两个日期的错误值,以及为什么正确值和我的程序值之间的差异是3天。我的代码示例应该按原样工作,可以在下面找到。任何建议都将不胜感激
daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Count the number of leap years
def countLeapYears(year, month):
if month <= 2:
year = year - 1
return int(year/4 - year/100 + year/400 )
# Determine the number of days between 0/00/0000 and the two dates and calculate the difference
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
days = 0
n1 = year1 * 365 + day1
for month in range (0, month1):
n1 += daysOfMonths[month]
n1 += countLeapYears(year1, month1)
n2 = year2 * 365 + day2
for month in range (0, month2):
n2 += daysOfMonths[month]
n2 += countLeapYears(year2, month2)
return n2 - n1
def test():
test_cases = [((2012,1,1,2012,2,28), 58),
((2011,6,30,2012,6,30), 366),
((2011,1,1,2012,8,8), 585 ),
((1900,1,1,1999,12,31), 36523)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
test()
daysOfMonths=[31,28,31,30,31,30,31,31,30,31]
#计算闰年的数量
年份(年、月):
如果月份在这些行中有一个off by one错误:
for month in range (0, month1):
...
for month in range (0, month2):
在Python中,列表的索引为零,但在程序中,月份是一个索引。因此,正确的代码是:
for month in range (month1 - 1)
...
for month in range (month2 - 1)
为什么不使用datetime
?只是尝试在没有内置函数的情况下实现它。在您的示例中,不应该超过365天,因为年份相差1
?很抱歉……这是一个输入错误。但问题是一样的