Here is an algorithm to calculate the number of elapsed months separating two dates. It accounts for the day of month and the fact that months have different lengths. It does not matter whether days and months are zero indexed.

Algorithm

Python implementation

date1 and date2 are datetime.date objects.

import calendar

def calculate_monthdelta(date1, date2):
    def is_last_day_of_the_month(date):
        days_in_month = calendar.monthrange(date.year, date.month)[1]
        return date.day == days_in_month
    imaginary_day_2 = 31 if is_last_day_of_the_month(date2) else date2.day
    monthdelta = (
        (date2.month - date1.month) +
        (date2.year - date1.year) * 12 +
        (-1 if date1.day > imaginary_day_2 else 0)
        )
    return monthdelta

Comments

Comment Atom Feed

There are no comments yet.

Add a Comment

You can use the Markdown syntax to format your comment.