如何在Python中确定两个日期之间的月份数?

use*_*ser 2 python datetime pandas

我有两列是 datetime64[ns] 对象。我正在尝试确定它们之间的月数。

这些列是:

city_clean['last_trip_date']
city_clean['signup_date']
Run Code Online (Sandbox Code Playgroud)

格式为 YYYY-MM-DD

我试过

from dateutil.relativedelta import relativedelta

city_clean['months_active'] = relativedelta(city_clean['signup_date'], city_clean['last_trip_date'])
Run Code Online (Sandbox Code Playgroud)

并得到以下错误:

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

有谁知道什么可能导致这个问题?我觉得这是计算月份数最准确的方法。

wp7*_*8de 5

这是熊猫,对吧?试试这样:

\n\n
# calculate the difference between two dates\ndf['diff_months'] = df['End_date'] - df['Start_date'] \n# converts the difference in terms of Months (timedelta64(1,\xe2\x80\x99M\xe2\x80\x99)-  capital M indicates Months)\ndf['diff_months']=df['diff_months']/np.timedelta64(1,'M') \n
Run Code Online (Sandbox Code Playgroud)\n\n

或者,如果您有正确的日期时间对象,

\n\n
def diff_month(d1, d2):\n    return (d1.year - d2.year) * 12 + d1.month - d2.month\n
Run Code Online (Sandbox Code Playgroud)\n