计算天数

99封情书 提交于 2019-11-26 17:50:29

计算两个日期之间的天数,需考虑闰年的情况。非闰年是 365 天。闰年是 366 天。点击 http://en.wikipedia.org/wiki/Leap_year#Algorithm for 查看闰年的规则。

def is_leap_year(year):#判断是否是闰年
    if year% 100 !=0:
        if year % 4 == 0 :
            return True
        else:
            return False
    elif year % 400 ==0:
        return True
    else:
        return False
def next_day(year, month, day):  #返回下一天
    if not is_leap_year(year):
        daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    else:
        daysOfMonths = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if day < daysOfMonths[month-1]:
        #print(daysOfMonths[month-1])
        next_year = year
        next_month = month
        next_day = day + 1
    elif month!=12:
        next_year = year
        next_month = month + 1
        next_day = 1
    elif month == 12:
        next_year = year + 1
        next_month = 1
        next_day = 1      
    return next_year,next_month,next_day     
next_day(2004, 2, 29)
def daysBetweenDates(year1, month1, day1, year2, month2, day2):#累计天数
    day_number = 1
    while next_day(year1, month1, day1)!= (year2, month2, day2):
        day_number += 1
        year1, month1, day1 = next_day(year1, month1, day1)
    return day_number
print(daysBetweenDates(2012,1,29,2012,3,1))

# Test routine

def test():
    test_cases = [((2012,1,1,2012,2,28), 58), 
                  ((2012,1,1,2012,3,1), 60),
                  ((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)
        print(result)
        if result != answer:
            print ("Test with data:", args, "failed")
        else:
            print ("Test case passed!")

test()

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!