Skip to content

Instantly share code, notes, and snippets.

@abdessamadely
Created December 29, 2020 22:04
Show Gist options
  • Save abdessamadely/44ed897f285e70ad2a350e6d0cd79693 to your computer and use it in GitHub Desktop.
Save abdessamadely/44ed897f285e70ad2a350e6d0cd79693 to your computer and use it in GitHub Desktop.
My solution to calculate days between two dates using python
def is_leap_year(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400:
return False
else:
return True
def days_between_dates(y1, m1, d1, y2, m2, d2):
days1 = 0
days2 = 0
days_of_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(y1):
days_of_months[1] = 29
month = 1
while(month < m1):
days1 += days_of_months[month]
month += 1
days1 += d1
if not is_leap_year(y2):
days_of_months[1] = 28
month = 1
while(month < m2):
days2 += days_of_months[month]
month += 1
days2 += d2
days = days2 - days1
while y1 < y2:
if is_leap_year(y1):
days += 366
else:
days += 365
y1 += 1
return days
print(str(days_between_dates(2012, 2, 1, 2012, 2, 2)) + ' day(s)')
print(str(days_between_dates(2012, 2, 1, 2014, 2, 2)) + ' day(s)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment