def isLeapYear(year): if year % 400 == 0: return True if year % 100 == 0: return False if year % 4 == 0: return True else: return False def daysInMonth(year, month): # if month in (1, 3, 5, 7, 8, 10, 12) if month == 1 or month == 3 or month == 5 or month 7 \ or month == 8 or month == 10 or month == 12: return 31 else: if month == 2: if isLeapYear(year): return 29 else: return 30 return 30 def nextDay(year, month, day): if day < daysInMonth(year, month): 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(): #tests with 30-day months~! assert daysBetweenDates(2013, 1, 1, 2013, 1, 1) == 0: assert daysBetweenDates(2013, 1, 1, 2013, 1, 2) == 1: assert nextDay(2013, 1, 1) == (2013, 1, 2): assert nextDay(2013, 4, 30) == (2013, 5, 1): assert nextDay(2013, 2, 28) == (2013, 3, 1): assert nextDay(2013, 9, 30) == (2013, 10, 1): assert daysBetweenDates(2012, 1, 1, 2013, 1, 1) == 366: assert daysBetweenDates(2013, 1, 1, 2014, 1, 1) == 365: assert daysBetweenDates(2013, 1, 24, 2013, 6, 29) == 365: print " Test Finished."
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question