Date subtraction leading to "TypeError: cannot perform truediv with this index type datetimeindex"

Viewed 3600

I am trying to subtract a date from a date column and calculating difference in terms of months:

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

But I get

> TypeError: cannot perform __truediv__ with this index type datetimeindex

How could I correct my code in order to find the difference in months?

2 Answers

I think you are missing a pair of parentheses:

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

^                                                       ^
this                                             and this 

Here is a short workaround using UNIX timestamps.

import pandas as pd
import numpy as np
x = (pd.Timestamp('2020-01-20'))
y = pd.to_datetime('2019-01-20')
print(f"Approximately {int((x.value - y.value)/2592000/ (10 ** 9))} months have passed.")

Note: I changed the second date since you are taking it from the df and we don't know what the df value is. Output enter image description here

Related