首页 > 代码库 > 求两个日期之间间隔的天数,Python实现

求两个日期之间间隔的天数,Python实现

代码如下

 1 def leap_year(y):   #判断是否是闰年 2     if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0: 3         return True 4     else: 5         return False 6          7 def days_in_month(y, m):    #判断每个月都有几天 8     if m in [1, 3, 5, 7, 8, 10, 12]: 9         return 3110     elif m in [4, 6, 9, 11]:11         return 3012     else:13         if leap_year(y):14             return 2915         else:16             return 2817             18 def days_this_year(year):   #判断今年共几天19     if leap_year(year):20         return 36621     else:22         return 36523             24 def days_passed(year, month, day):  #判断今年过了几天25     m = 126     days = 027     while m < month:28         days += days_in_month(year, m)29         m += 130     return days + day31 32 def daysBetweenDates(year1, month1, day1, year2, month2, day2):33     ##34     # Your code here.35     ##36     if year1 == year2:37         return days_passed(year2, month2, day2) - days_passed(year1, month1, day1)38     else:39         sum1 = 040         y1 = year141         while y1 < year2:42             sum1 += days_this_year(y1)43             y1 += 144         return sum1-days_passed(year1,month1,day1)+days_passed(year2,month2,day2)

 

用下面的代码进行正确性测试

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)        if result != answer:            print "Test with data:", args, "failed"        else:            print "Test case passed!"test()

 

测试结果如下