gpt4 book ai didi

Python,计算两个日期之间的天数在一种特定情况下返回错误值

转载 作者:行者123 更新时间:2023-12-01 04:09:55 25 4
gpt4 key购买 nike

我编写了一个程序来计算两个日期之间的天数,除了一种情况外,它工作正常。如果我想计算两个日期之间的天数,并且结束日期是二月,则天数不正确(正好缺少三天)

示例:

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()

最佳答案

这些行中存在差一错误:

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)

关于Python,计算两个日期之间的天数在一种特定情况下返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35104022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com