Skip to content

Instantly share code, notes, and snippets.

@rathankalluri
Last active March 19, 2017 12:25
Show Gist options
  • Save rathankalluri/61b380945f2ca0cf1c1c33622edae2dc to your computer and use it in GitHub Desktop.
Save rathankalluri/61b380945f2ca0cf1c1c33622edae2dc to your computer and use it in GitHub Desktop.
Difference between dates (Not using Built-In Functions and Lists)
#!/usr/bin/python
# This program is written without using any built-in functions
# Not using Lists, as a practice for students learning Python
def isLeapYear(year):
if ((year%4 == 0 and year%100 != 0)) or year%400 == 0:
return True
return False
def daysInMonth(year, month):
if month in {1,3,5,7,8,10,12}:
days = 31
if month in {4,6,9,11}:
days = 30
if month == 2:
if isLeapYear(year):
days = 29
else:
days = 28
return days
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)
diff = 0
while dateIsBefore(year1, month1, day1, year2, month2, day2):
year1, month1, day1 = nextDay(year1, month1, day1)
diff += 1
return diff
print daysBetweenDates(2011,6,30,2012,6,30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment