unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'

Viewed 31

I was trying to create a RFM Model and I'm trying to get delta value (day) by subtracting the purchase date and given period of date. the code :

latest_date = dt.datetime(2022,6,30)
RFMScore = df.groupby('user_id').agg({'created_at': lambda x: (latest_date - x.max()).days, 'order_id': lambda x: len(x), 'total': lambda x: x.sum()})
RFMScore['created_at'] = RFMScore['created_at'].astype(int)
RFMScore.rename(columns={'created_at': 'Recency', 
                         'order_id': 'Frequency', 
                         'total': 'Monetary'}, inplace=True)

RFMScore.reset_index().head()
return df

this code returns unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'

1 Answers

latest_date is a datetime object, but you are substracting a date object x.max()

You can easily convert a date to datetime as follows:

d = x.max()
latest_date - datetime.datetime(d.year, d.month, d.day)
Related