TypeError: unsupported operand type(s) for +: 'DatetimeArray' and 'relativedelta'

3.9k Views Asked by At

I am trying to convert a column called Month_Next from a dataframe called df_actual from the last day of one month to the first day of the next. The column looks like this:

enter image description here

And I'm using

df_actual.Month_Next = pd.to_datetime(df_actual.Month_Next) + relativedelta(months=1, day=1)

and getting this error.

TypeError: unsupported operand type(s) for +: 'DatetimeArray' and 'relativedelta'

Which makes no sense to me since this exact code works in a different notebook where Month_Next comes in as I believe a Timestamp object like so

enter image description here

Any ideas as to what's going on here?

2

There are 2 best solutions below

0
On BEST ANSWER

This works just fine:

Month_Next = df_actual.AsOfDate + pd.DateOffset(months =1) - pd.offsets.MonthBegin(1)
2
On

You are trying to add date types from different packages - one from pandas and the other dateutil. Try converting them to pandas types (use pandas.Timedelta).

Example:

import pandas as pd

datetime_arr = pd.arrays.DatetimeArray(pd.Series([0, 1, 2, 3, 4]))

print(datetime_arr)
print(datetime_arr + pd.Timedelta(10, 'd'))

Output:

<DatetimeArray>
[          '1970-01-01 00:00:00', '1970-01-01 00:00:00.000000001',
 '1970-01-01 00:00:00.000000002', '1970-01-01 00:00:00.000000003',
 '1970-01-01 00:00:00.000000004']
Length: 5, dtype: datetime64[ns]
<DatetimeArray>
[          '1970-01-11 00:00:00', '1970-01-11 00:00:00.000000001',
 '1970-01-11 00:00:00.000000002', '1970-01-11 00:00:00.000000003',
 '1970-01-11 00:00:00.000000004']
Length: 5, dtype: datetime64[ns]