{"record":{"id":"c43dd40e4e3c9057","repo":"pandas-dev/pandas","slug":"overflow-in-int64-multiplication","errorCode":null,"errorMessage":"Overflow in int64 multiplication","messagePattern":"Overflow in int64 multiplication","errorType":"exception","errorClass":"OutOfBoundsTimedelta","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/timedeltas.py","lineNumber":494,"sourceCode":"        if non_nan.size and np.max(np.abs(non_nan), initial=0.0) >= 2.0**63:\n            raise OutOfBoundsTimedelta(\"Overflow in timedelta multiplication\")\n        # NaN-to-int cast is platform-dependent; substitute 0 then re-mask as NaT\n        if nan_mask.any():\n            f_result = np.where(nan_mask, 0.0, f_result)\n        i8_result = f_result.astype(\"i8\")\n        nat_out = self_mask | nan_mask\n        if nat_out.any():\n            i8_result[nat_out] = iNaT\n        result = i8_result.view(self._ndarray.dtype)\n        return type(self)._simple_new(result, dtype=result.dtype)\n\n    def _mul_int_overflowsafe(self, i8_other: npt.NDArray[np.int64]) -> Self:\n        # GH#43178: mul_overflowsafe raises the low-level OverflowError; surface\n        #  it as OutOfBoundsTimedelta to match pandas' other td64 overflow paths.\n        try:\n            i8_result = mul_overflowsafe(self.asi8, i8_other)\n        except OverflowError as err:\n            raise OutOfBoundsTimedelta(\"Overflow in int64 multiplication\") from err\n        result = i8_result.view(self._ndarray.dtype)\n        return type(self)._simple_new(result, dtype=result.dtype)\n\n    @unpack_zerodim_and_defer(\"__mul__\")\n    def __mul__(self, other) -> Self:\n        if is_scalar(other):\n            if lib.is_bool(other):\n                raise TypeError(\n                    f\"Cannot multiply '{self.dtype}' by bool, explicitly cast to \"\n                    \"integers instead\"\n                )\n            if lib.is_integer(other):\n                # GH#43178: detect int64 overflow rather than silently wrapping\n                #  in the i8 cast below (e.g. a multiplier outside int64 bounds).\n                # TODO(numpy>=2.5): numpy detects this natively (numpy GH-31378)\n                #  but raises OverflowError; once the numpy floor is >= 2.5, drop\n                #  mul_overflowsafe and re-wrap numpy's error as\n                #  OutOfBoundsTimedelta. The float path isn't covered and stays.","sourceCodeStart":476,"sourceCodeEnd":512,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/timedeltas.py#L476-L512","documentation":"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.","triggerScenarios":"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.","commonSituations":"Broadcasting a count column across a duration column; aggregation pipelines that scale durations; unsigned multipliers above int64.max wrapping to negative.","solutions":["Downcast the duration array to a coarser supported unit before multiplying: td_arr.astype('timedelta64[s]') * counts.","Reduce the multiplier or split the multiplication into smaller batches.","If the product genuinely exceeds int64 ns range, represent results as float seconds via .dt.total_seconds()."],"exampleFix":"# before\narr * big_int_array  # OutOfBoundsTimedelta\n# after\narr.astype('timedelta64[s]') * big_int_array","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef safe_int_mul(td_arr, int_arr):\n    int_arr = np.asarray(int_arr, dtype='i8')\n    peak = np.max(np.abs(td_arr.asi8)) * np.max(np.abs(int_arr))\n    if peak >= 2**63:\n        td_arr = td_arr.astype('timedelta64[s]')\n    return td_arr * int_arr","typeGuard":"import numpy as np\ndef int_mul_will_overflow(td_arr, int_arr) -> bool:\n    a = np.asarray(int_arr, dtype='i8')\n    return np.max(np.abs(td_arr.asi8)) * np.max(np.abs(a)) >= 2**63","tryCatchPattern":"from pandas.errors import OutOfBoundsTimedelta\ntry:\n    return td_arr * counts\nexcept OutOfBoundsTimedelta as e:\n    if 'Overflow in int64 multiplication' in str(e):\n        return td_arr.astype('timedelta64[s]') * counts\n    raise","preventionTips":["Cast duration arrays to coarser units before scaling by counts.","Range-check int multipliers before broadcasting.","Use .dt.total_seconds() for products exceeding int64 ns range."],"tags":["timedelta","overflow","int-multiplication","outofbounds"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}