Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine number of months between two dates in Python?

I have two columns that are datetime64[ns] objects. I am trying to determine the number of months between them.

The columns are:

city_clean['last_trip_date']
city_clean['signup_date']

Format is YYYY-MM-DD

I tried

from dateutil.relativedelta import relativedelta

city_clean['months_active'] = relativedelta(city_clean['signup_date'], city_clean['last_trip_date'])

And get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Does anyone know what could cause this issue? I feel like this is the most accurate way to calculate the number of months.

like image 515
user Avatar asked Feb 03 '26 22:02

user


1 Answers

This is Pandas, right? Try it like this:

# calculate the difference between two dates
df['diff_months'] = df['End_date'] - df['Start_date'] 
# converts the difference in terms of Months (timedelta64(1,’M’)-  capital M indicates Months)
df['diff_months']=df['diff_months']/np.timedelta64(1,'M') 

Or, if you have proper datetimes objects,

def diff_month(d1, d2):
    return (d1.year - d2.year) * 12 + d1.month - d2.month
like image 118
wp78de Avatar answered Feb 05 '26 12:02

wp78de



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!