1

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.

wp78de
  • 17,272
  • 6
  • 36
  • 68
user
  • 443
  • 4
  • 14

2 Answers2

2

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
wp78de
  • 17,272
  • 6
  • 36
  • 68
1

The first thing that comes to my mind...

>>> from datetime import datetime, timedelta

>>> dt1 = datetime(year=2020, month=3, day=1)
>>> dt2 = datetime(year=2020, month=5, day=1)
>>> # delta = dt2-dt1
>>> delta = abs(dt2-dt1)

>>> delta
datetime.timedelta(61)

>>> delta.days
61
Gergely M
  • 440
  • 4
  • 11