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

时间:2016-01-30 16:17:31

标签: python

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

示例:

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

1 个答案:

答案 0 :(得分:2)

这些行中有一个错误的错误:

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)