Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month subtract month

Tags:

python

pandas

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 someone 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'))
like image 370
unclegood Avatar asked Mar 11 '23 09:03

unclegood


2 Answers

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

date1.to_period("M") - date2.to_period("M")
# 7
like image 180
Psidom Avatar answered Mar 31 '23 07:03

Psidom


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

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)

The ouput will be

6.16129032258
like image 29
Yoel Zeldes Avatar answered Mar 31 '23 08:03

Yoel Zeldes