# By Websten from forums # # Given your birthday and the current date, calculate your age in days. # Account for leap days. # # Assume that the birthday and current date are correct dates (and no # time travel). # month_lengths = [0,31,28,31,30,31,30,31,31,30,31,30,31] def is_leap_year(y): if y % 400 == 0: #example 2000 return True if y % 100 == 0: #example 1700 return False if y%4 == 0: return True return False def fullYears(year1, year2): tdays = 0 span = year2-year1 if span > 1: span = span + 1 tyear = year1 + 1 while tyear < year2: if is_leap_year(tyear): tdays = tdays + 366 else: tdays = tdays + 365 tyear = tyear + 1 return tdays def rest_of_year(month1, day1, year1): days_left = month_lengths[month1] - day1 monthN = month1 + 1 while monthN <= 12: days_left = days_left + month_lengths[monthN] if is_leap_year(year1) and monthN == 2: days_left = days_left + 1 monthN = monthN + 1 return days_left def up_to_year(month2,day2,year2): monthN = 1 year_to_date = day2 while monthN < month2: year_to_date = year_to_date + month_lengths[monthN] monthN = monthN + 1 if is_leap_year(year2) and monthN == 2: year_to_date = year_to_date + 1 return year_to_date def daysBetweenDates(year1, month1, day1, year2, month2, day2): if year1 != year2: days = fullYears(year1,year2) days2 = rest_of_year(month1, day1, year1) days3 = up_to_year(month2,day2,year2) else: days3 = 0 sM = month1 + 1 days = month_lengths[month1] - day1 days2 = day2 while sM < month2: days3 = days3 + month_lengths[sM] if (is_leap_year(year1) and sM==2): days3 = days3 + 1 sM = sM + 1 print str(days) + "," + str(days2) + "," + str(days3) return days + days2 + days3 # 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) if result != answer: print "Test with data:", args, "failed" else: print "Test with: ", args, " case passed!" test()
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