Month subtracts month

I am trying to get the number of months between date 1 and date 2 below in months. The result is only 2016-12 minus 2016-5, which is 7. I only know how to get the days in int, can anyone teach me how to get the result in mths, which is 7?

import pandas as pd
import numpy as np

date1=pd.to_datetime('2016-12-1')
date2=pd.to_datetime('2016-5-27')

print((date1-date2)/np.timedelta64(1,'D'))
+4
source share
2 answers

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

date1.to_period("M") - date2.to_period("M")
# 7
+5
source

If you do not need a day for a month, you can do the following:

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

Dates for the same month, for example. '2016-12-31' and '2016-12-1' will give you 0.

, , . . 30 , 0/30, 29/30. :

from calendar import monthrange

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

def get_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)

6.16129032258
+2

Source: https://habr.com/ru/post/1664047/


All Articles