Interestingly enough, your code outputs to: 5
which means, as suggested in the comments, that you are probably interested in the duration of each month and you do not want to round your results. Unfortunately the timedelta
object will not work for you in this case because by definition, a time difference does not hold the information you need to obtain the duration of the months of interest to you.
You should probably take a look here:
Python: Difference of 2 datetimes in months
where they discuss a solution using calendar
instead of dateutil
.
Otherwise, if you are happy with an approximated (and rounded) estimate, you could go close enough by doing:
DAYS_PER_MONTH = 30 # or 365.0 / 12.0 for more precision
datetime_diff = date2 - date1
print(datetime_diff.days / DAYS_PER_MONTH) # '//' for floored result
If you want to get back to some code that works with your data (but not with all data, because of e.g. leap years, leap seconds, etc.) have a look here:
MONTH_NUM_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
YEAR_LENGTH = 365.25 # average year duration, including leap years
def num_days_in_months(
begin_month, end_month, month_duration=MONTH_NUM_DAYS):
begin_month, end_month = sorted((begin_month, end_month))
return sum(month_duration[begin_month:end_month])
def get_num_months(begin_date, end_date, num_days_per_year=YEAR_LENGTH):
begin_month = begin_date.month
end_month = end_date.month
month_diff = abs(end_month - begin_month)
num_days = (end_date - begin_date).days
num_days_within_year = num_days % num_days_per_year
num_months = num_days // num_days_per_year
num_days_max = num_days_in_months(begin_month, end_month)
print(num_months, month_diff)
if num_days_within_year < num_days_max:
num_months += month_diff - 1
else:
num_months += month_diff
return num_months