首页 > 解决方案 > 如何确定Python中两个日期之间的月数?

问题描述

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

这些列是:

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

格式为 YYYY-MM-DD

我试过了

from dateutil.relativedelta import relativedelta

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

并得到以下错误:

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

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

标签: pythonpandasdatetime

解决方案


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

# 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') 

或者,如果您有适当的日期时间对象,

def diff_month(d1, d2):
    return (d1.year - d2.year) * 12 + d1.month - d2.month

推荐阅读