标签:style blog http color for ar 2014 div
代码如下
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 31 10 elif m in [4, 6, 9, 11]: 11 return 30 12 else: 13 if leap_year(y): 14 return 29 15 else: 16 return 28 17 18 def days_this_year(year): #判断今年共几天 19 if leap_year(year): 20 return 366 21 else: 22 return 365 23 24 def days_passed(year, month, day): #判断今年过了几天 25 m = 1 26 days = 0 27 while m < month: 28 days += days_in_month(year, m) 29 m += 1 30 return days + day 31 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 = 0 40 y1 = year1 41 while y1 < year2: 42 sum1 += days_this_year(y1) 43 y1 += 1 44 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()
测试结果如下
求两个日期之间间隔的天数,Python实现,布布扣,bubuko.com
标签:style blog http color for ar 2014 div
原文地址:http://www.cnblogs.com/jk123vip/p/3918637.html