numpy/numpy

BUG: truediv with object array and timedelta64 raises

Closed this issue · 1 comments

Describe the issue:

Dividing a NumPy array of object dtype holding Python timedeltas by np.timedelta64 raises an exception, where as dividing elementwise is successful. I would have expected the op to act elementwise successfully.

Reproduce the code example:

from datetime import timedelta
import numpy as np

arr = np.array([timedelta(seconds=1)], dtype="object")
scalar = np.timedelta64(1, 's')

print(arr[0] / scalar)
# 1.0

print(arr / 2)
# [datetime.timedelta(microseconds=500000)]

print(arr / scalar)
# numpy._core._exceptions._UFuncBinaryResolutionError: ufunc 'divide' cannot use operands with types dtype('O') and dtype('<m8[s]')

Error message:

Python and NumPy Versions:

Python 3.11.13
numpy 2.3.4

Runtime Environment:

No response

Context for the issue:

Encountered in pandas-dev/pandas#62712

cc @seberg

I’ve opened a merge request to fix this behavior.

Just as a note, if you use dtype="m8", you can avoid this error and perform the calculation much more efficiently.
(You might already be aware of this, but I wanted to mention it just in case.)