1

I need to subtract x months from a specific date in python and tried several ways, but get the following errors:


dates = np.array(['2023-02-28T00:00:00.000000000','2022-12-31T00:00:00.000000000','2019-01-01T00:00:00.000000000'], dtype=np.datetime64)

dates + np.timedelta64(-5,'M')
numpy.core._exceptions._UFuncInputCastingError: Cannot cast ufunc 'add' input 1 from dtype('<m8[M]') to dtype('<m8[ns]') with casting rule 'same_kind'

dates + relativedelta(months=-5)
numpy.core._exceptions._UFuncBinaryResolutionError: ufunc 'add' cannot use operands with types dtype('<M8[ns]') and dtype('O')

datetime.fromtimestamp(dates.astype(datetime) / 1e9) + relativedelta(months=-5)
TypeError: only integer scalar arrays can be converted to a scalar index

What is the problem here?

Serge Kashlik
  • 361
  • 4
  • 16

1 Answers1

1

relativedelta is designed to work with python's native datetime objects, not numpy datetime64 object. Therefore, you should use datetime instead of np.timedelta64 like so:

from datetime import datetime
from dateutil.relativedelta import relativedelta

t = datetime(2023, 2, 28)
result = t - relativedelta(months=-5)
print(result)


#output

2023-07-28 00:00:00

To understand more why np.timedelta cannot work with years and months, look at here

Hamzah
  • 8,175
  • 3
  • 19
  • 43
  • 1
    conversion from numpy to py datetime is *relatively* straigt-forward, e.g. `datetime.fromtimestamp(t.astype(datetime)/1e9)` for the example in the OP. – FObersteiner Mar 21 '23 at 11:01
  • how can the same be doe for an array? I edited the question. and also why does the ```np.timedelta``` not work here? – Serge Kashlik Mar 21 '23 at 11:16
  • @SergeKashlik Please, read this to know why np.timedelta does not work here: https://stackoverflow.com/a/40290946/16733101 – Hamzah Mar 21 '23 at 11:18