Ryan Lodter    Projects    Posts    About    Search

How to Account for Leap Years when Computing Date Differences

The Problem

I needed a Python script that takes in two days and outputs the difference between then in days. When testing my script I realized I wasn’t accounting for leap years so I was consistently off when the gap between the dates overlapped leap years.

My Solution

Setup

Declare number of days in each (non leap year) month using a dictionary.

months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}

Get and parse the start and end dates into variables.

#get start date
date = input("Enter start date (m-d-year): ")

dash_index = date.index('-')
month_start = int(date[:dash_index])
date = date[dash_index + 1:]

dash_index = date.index('-')
day_start = int(date[:dash_index])
date = date[dash_index + 1:]

year_start = int(date)

#get end date
date = input("Enter end date (m-d-year): ")

dash_index = date.index('-')
month_end = int(date[:dash_index])
date = date[dash_index + 1:]

dash_index = date.index('-')
day_end = int(date[:dash_index])
date = date[dash_index + 1:]

year_end = int(date)

Now all I need to do is calculate the difference.

First I initialize the difference variable.

difference = 0

Now, the reason I wrote this post. Calculate the number of days that need to be added for leap years.

The first case is leap years between the two dates not including the start or end year.

num_leap_years = 0

for i in range(year_start + 1, year_end):
	if i % 4 == 0:
		num_leap_years += 1

The next case is if the start date is in a leap year and before March, we need to add a day.

if year_start % 4 == 0:
	if month_start < 3:
		num_leap_years += 1

The last case is if the end date is in a leap year and after February, we need to add a day.

if year_end % 4 == 0:
	if month_end > 2:
		num_leap_years += 1

Next I calculate the number of days between the dates including the leap years correction.

#find number of years between the two dates	
year_difference = year_end - year_start

#add the number of days between the years including the leap days
if year_difference > 0:
	difference += (365 * year_difference) + num_leap_years

#add number of days for the ending months
for i in range(month_start, month_end + 1):
	difference += months[i]
#subtract the number of days for the starting months
difference = difference - day_start
difference = difference - (months[month_end] - day_end)

Finally I print out the difference in days.

print(str(difference) + " days")