{"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":511,"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            other = _exact_if_integral(other)\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","sourceCodeStart":493,"sourceCodeEnd":529,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/timedeltas.py#L493-L529","documentation":"Raised by TimedeltaArray._mul_int_overflowsafe, which delegates to the cython mul_overflowsafe for safe int64 multiplication. When that low-level routine detects a product exceeding int64 range it raises OverflowError; pandas re-raises it as OutOfBoundsTimedelta to stay consistent with its other timedelta overflow paths. This covers the array-by-int path (scalar int overflow is caught earlier in __mul__).","triggerScenarios":"Multiplying a timedelta64 array by an int array where at least one product exceeds ±2**63 nanoseconds, e.g. `pd.to_timedelta(np.arange(10), unit='D') * np.array([10**18], dtype='i8')`.","commonSituations":"Vectorized scaling of durations by large integer weights; broadcasting an int array/Series multiplier against ns-resolution timedeltas.","solutions":["Scale down the integer multiplier(s) so every element's product stays within ±2**63 ns.","Switch to a float multiplier and operate in coarser units (total_seconds) if you need magnitudes beyond the ns int64 range.","Clip either operand to a safe range before multiplying."],"exampleFix":"# before\npd.to_timedelta(np.arange(5), unit='D') * np.full(5, 10**18)  # OutOfBoundsTimedelta\n\n# after\npd.to_timedelta(np.arange(5), unit='D') * np.array([1, 2, 3, 4, 5])","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef td_int_mul_is_safe(td_ns_values, int_arr):\n    a = np.asarray(td_ns_values, dtype='i8')\n    b = np.asarray(int_arr, dtype='i8')\n    # NaT-safe extreme bound\n    a_safe = np.where(a == np.int64(np.iinfo(np.int64).min), 0, a)\n    lo = int(a_safe.min()) * int(b.min())\n    hi = int(a_safe.max()) * int(b.max())\n    return max(abs(lo), abs(hi)) <= np.iinfo(np.int64).max","typeGuard":"null","tryCatchPattern":"from pandas.errors import OutOfBoundsTimedelta\ntry:\n    result = td * int_weights\nexcept OutOfBoundsTimedelta:\n    result = td.dt.total_seconds() * int_weights","preventionTips":["Cast weight arrays to int64 and pre-check extreme products.","Use coarser-unit arithmetic when weights are large."],"tags":["timedelta","overflow","multiplication","outofbounds","int64"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}