pandas-dev/pandas · error · OutOfBoundsTimedelta

Overflow in int64 multiplication

Error message

Overflow in int64 multiplication

What it means

Raised by TimedeltaArray._mul_int_overflowsafe when the Cython mul_overflowsafe detects int64 overflow multiplying the nanosecond ticks by an integer array. GH#43178: the low-level OverflowError is re-wrapped as OutOfBoundsTimedelta to keep pandas' td64 overflow surfaces consistent. This catches array-multiplier cases the scalar fast path did not cover.

Source

Thrown at pandas/core/arrays/timedeltas.py:494

        if non_nan.size and np.max(np.abs(non_nan), initial=0.0) >= 2.0**63:
            raise OutOfBoundsTimedelta("Overflow in timedelta multiplication")
        # NaN-to-int cast is platform-dependent; substitute 0 then re-mask as NaT
        if nan_mask.any():
            f_result = np.where(nan_mask, 0.0, f_result)
        i8_result = f_result.astype("i8")
        nat_out = self_mask | nan_mask
        if nat_out.any():
            i8_result[nat_out] = iNaT
        result = i8_result.view(self._ndarray.dtype)
        return type(self)._simple_new(result, dtype=result.dtype)

    def _mul_int_overflowsafe(self, i8_other: npt.NDArray[np.int64]) -> Self:
        # GH#43178: mul_overflowsafe raises the low-level OverflowError; surface
        #  it as OutOfBoundsTimedelta to match pandas' other td64 overflow paths.
        try:
            i8_result = mul_overflowsafe(self.asi8, i8_other)
        except OverflowError as err:
            raise OutOfBoundsTimedelta("Overflow in int64 multiplication") from err
        result = i8_result.view(self._ndarray.dtype)
        return type(self)._simple_new(result, dtype=result.dtype)

    @unpack_zerodim_and_defer("__mul__")
    def __mul__(self, other) -> Self:
        if is_scalar(other):
            if lib.is_bool(other):
                raise TypeError(
                    f"Cannot multiply '{self.dtype}' by bool, explicitly cast to "
                    "integers instead"
                )
            if lib.is_integer(other):
                # GH#43178: detect int64 overflow rather than silently wrapping
                #  in the i8 cast below (e.g. a multiplier outside int64 bounds).
                # TODO(numpy>=2.5): numpy detects this natively (numpy GH-31378)
                #  but raises OverflowError; once the numpy floor is >= 2.5, drop
                #  mul_overflowsafe and re-wrap numpy's error as
                #  OutOfBoundsTimedelta. The float path isn't covered and stays.

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Downcast the duration array to a coarser supported unit before multiplying: td_arr.astype('timedelta64[s]') * counts.
  2. Reduce the multiplier or split the multiplication into smaller batches.
  3. If the product genuinely exceeds int64 ns range, represent results as float seconds via .dt.total_seconds().

Example fix

# before
arr * big_int_array  # OutOfBoundsTimedelta
# after
arr.astype('timedelta64[s]') * big_int_array
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def safe_int_mul(td_arr, int_arr):
    int_arr = np.asarray(int_arr, dtype='i8')
    peak = np.max(np.abs(td_arr.asi8)) * np.max(np.abs(int_arr))
    if peak >= 2**63:
        td_arr = td_arr.astype('timedelta64[s]')
    return td_arr * int_arr

Type guard

import numpy as np
def int_mul_will_overflow(td_arr, int_arr) -> bool:
    a = np.asarray(int_arr, dtype='i8')
    return np.max(np.abs(td_arr.asi8)) * np.max(np.abs(a)) >= 2**63

Try / catch

from pandas.errors import OutOfBoundsTimedelta
try:
    return td_arr * counts
except OutOfBoundsTimedelta as e:
    if 'Overflow in int64 multiplication' in str(e):
        return td_arr.astype('timedelta64[s]') * counts
    raise

Prevention

When it happens

Trigger: Calling `td_arr * int_array` where the elementwise products exceed int64 range (e.g. days-scale durations times large counts). Reached when the scalar extreme-bound check at line 525 does not short-circuit, falling through to _mul_int_overflowsafe at line 528.

Common situations: Broadcasting a count column across a duration column; aggregation pipelines that scale durations; unsigned multipliers above int64.max wrapping to negative.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/c43dd40e4e3c9057. Report an issue: GitHub.