獲得兩個日期中間間隔的天數
阿新 • • 發佈:2019-02-18
方法一:
def isLeapYear(year): ## # Your code here. Return True or False # Pseudo code for this algorithm is found at # http://en.wikipedia.org/wiki/Leap_year#Algorithm ## return year%400==0 or year%4==0 and year%100!=0 daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def daysAdd(y1, m1, d1): if isLeapYear(y1): daysOfMonths[1] = 29 else: daysOfMonths[1] = 28 d1 = d1+1 if d1>daysOfMonths[m1-1]: d1 = 1 y1,m1 = mounthAdd(y1,m1) return y1,m1,d1 def mounthAdd(y1, m1): m1 = m1+1 if m1>12: m1 = 1 y1 = y1+1 return y1,m1 def daysBetweenDates(y1, m1, d1, y2, m2, d2): day = 0 while True: y1,m1,d1 = daysAdd(y1,m1,d1) day+=1 if y1==y2 and m1==m2 and d1==d2: break return day # print isLeapYear(2100) print daysBetweenDates(2017,12,26,2017,12,27)
方法二:
def leap(year): if year%400==0: return True elif year%100==0: return False elif year%4==0: return True else: return False def dayofmonth(month,year): days=[0,31,28,31,30,31,30,31,31,30,31,30,31] if month!=2: return days[month] return days[2]+int(leap(year)) def nextDay(year, month, day): """Simple version: assume every month has 30 days""" if day < dayofmonth(month,year): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1 def dateIsBefore(year1, month1, day1, year2, month2, day2): """Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False.""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: return day1 < day2 return False def daysBetweenDates(year1, month1, day1, year2, month2, day2): """Returns the number of days between year1/month1/day1 and year2/month2/day2. Assumes inputs are valid dates in Gregorian calendar.""" # program defensively! Add an assertion if the input is not valid! assert not dateIsBefore(year2, month2, day2, year1, month1, day1) days = 0 while dateIsBefore(year1, month1, day1, year2, month2, day2): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days def test(): test_cases = [((2012,9,30,2012,10,30),30), ((2012,1,1,2013,1,1),366), ((2012,9,1,2012,9,4),3), ((2013,1,1,1999,12,31), "AssertionError")] for (args, answer) in test_cases: try: result = daysBetweenDates(*args) if result != answer: print "Test with data:", args, "failed" else: print "Test case passed!" except AssertionError: if answer == "AssertionError": print "Nice job! Test case {0} correctly raises AssertionError!\n".format(args) else: print "Check your work! Test case {0} should not raise AssertionError!\n".format(args) test()