# 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). # def leap_year(year): if year%4==0: if year%100==0: if year%400==0: return True else: return False else: return True else: return False def daysBetweenDates(year1, month1, day1, year2, month2, day2): ## date1=(month1-1)*30+day1 date2=(month2-1)*30+day2+(year2-year1)*365 if leap_year(year1)==True: if month1>2: date1=date1+1 year=year1 while year<year2: if leap_year(year)==True: date2=date2+1 year=year+1 if leap_year(year2)==True: if month2>2: date2=date2+1 month=1 while month<month1: if month==1 or month==3 or month==5 or month==7 or month==8 or month==10: date1=date1+1 if month==2: date1=date1-2 month=month+1 month=1 while month<month2: if month==1 or month==3 or month==5 or month==7 or month==8 or month==10: date2=date2+1 if month==2: date2=date2-2 month=month+1 age=date2-date1 return age ## # 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 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