首页 > 解决方案 > 导致“TypeError:无法使用此索引类型 datetimeindex 执行 truediv”的日期减法

问题描述

我试图从日期列中减去一个日期并计算月份的差异:

pd.to_datetime('2020-01-20')-pd.to_datetime(df['date'])/np.timedelta64(1,'M')

但我明白了

> TypeError: cannot perform __truediv__ with this index type datetimeindex

我怎样才能更正我的代码以找出几个月的差异?

标签: pythonpandasdataframedate

解决方案


我认为您缺少一对括号:

(pd.to_datetime('2020-01-20')-pd.to_datetime(df['date'])) / pd.to_timedelta(`1min')

^                                                       ^
this                                             and this 

推荐阅读