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'))
You can convert the date to month period and then do the subtraction:
date1.to_period("M") - date2.to_period("M")
# 7
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With