Skip to content Skip to sidebar Skip to footer

Month Subtract Month

I am trying to get number of months between date1 and date2 below in months. The result is just simply 2016-12 minus 2016-5, which is 7. I only know how to get days in int, can som

Solution 1:

You can convert the date to month period and then do the subtraction:

date1.to_period("M") - date2.to_period("M")
# 7

Solution 2:

If you don't care about the day within the month, you can do like this:

date1.year * 12 + date1.month - (date2.year * 12 + date2.month)

Dates within the same month, e.g. '2016-12-31' and '2016-12-1', will give you 0.

If you do want to account for the day within the month, you can calculate the fraction of the month passed until the given day. E.g. if a month has 30 days, then the first day's fraction is 0/30, and the last day's fraction is 29/30. This code snippet will do it:

from calendar import monthrange

defget_frac_of_month(date):
    # monthrange returns a tuple where the second entry is the number of days in the monthreturn1. * (date.day - 1) / monthrange(date.year, date.month)[1]

defget_month_diff(date1, date2):
    return date1.year * 12 + date1.month + get_frac_of_month(date1) - (date2.year * 12 + date2.month + get_frac_of_month(date2))

print get_month_diff(date1, date2)

The ouput will be

6.16129032258

Post a Comment for "Month Subtract Month"