pandas-dev/pandas · error · OutOfBoundsTimedelta

Overflow in timedelta division

Error message

Overflow in timedelta division

What it means

Raised as OutOfBoundsTimedelta from _check_float_div_overflow when dividing a timedelta array by a float whose quotient (in nanoseconds) would exceed int64 bounds. Numpy would otherwise silently saturate; pandas raises instead (GH#43178). NaT dividends and zero/NaN divisors are excluded since numpy returns NaT for them.

Source

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

        other_arr = np.asarray(other)
        if other_arr.ndim == 0 and i8.size:
            divisor = other_arr.item()
            if divisor == 0 or np.isnan(divisor):
                # numpy returns all-NaT; nothing to check
                return
            # The extreme elements bound all quotients, so most cases resolve
            #  without the full per-element check below. A NaT (int64.min)
            #  dividend can only false-trip this bound, never pass an
            #  overflowing quotient.
            low_quot = i8.min() / divisor
            high_quot = i8.max() / divisor
            if max(abs(low_quot), abs(high_quot)) < 2.0**63:
                return
        with np.errstate(divide="ignore", invalid="ignore"):
            f_quot = i8 / other_arr
        exclude_mask = (i8 == iNaT) | np.isnan(f_quot) | (other_arr == 0)
        if np.max(np.abs(f_quot), initial=0.0, where=~exclude_mask) >= 2.0**63:
            raise OutOfBoundsTimedelta("Overflow in timedelta division")

    def _scalar_divlike_op(self, other, op):
        """
        Shared logic for __truediv__, __rtruediv__, __floordiv__, __rfloordiv__
        with scalar 'other'.
        """
        if isinstance(other, self._recognized_scalars):
            other = Timedelta(other)
            # mypy assumes that __new__ returns an instance of the class
            # github.com/python/mypy/issues/1020
            if cast("Timedelta | NaTType", other) is NaT:
                # specifically timedelta64-NaT
                res = np.empty(self.shape, dtype=np.float64)
                res.fill(np.nan)
                return res

            # otherwise, dispatch to Timedelta implementation
            return op(self._ndarray, other)

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Convert via to_timedelta with explicit unit instead of arithmetic division.
  2. Increase the divisor (use coarser units) or reduce the dividend magnitude.
  3. If overflow is expected, switch to float64 representation of seconds before dividing.

Example fix

// before
out = td_series / 1e-9  # magnifies to ns, overflows

// after
out = td_series.dt.total_seconds() / 1e-9
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np
i8 = td.asi8 if hasattr(td, 'asi8') else td.values.view('i8')
q = np.asarray(i8) / float(divisor)
if not np.all(np.abs(q[~np.isnan(q)]) < 2.0**63):
    raise ValueError('division would overflow int64 timedelta bounds')

Type guard

def would_overflow_td_div(td_arr, divisor) -> bool:
    import numpy as np
    i8 = np.asarray(td_arr).view('i8') if np.asarray(td_arr).dtype.kind == 'm' else None
    if i8 is None: return False
    q = i8 / float(divisor)
    return bool(np.nanmax(np.abs(q)) >= 2.0**63) if q.size else False

Try / catch

try:
    out = td / divisor
except OutOfBoundsTimedelta as e:
    if 'Overflow in timedelta division' in str(e):
        out = td.dt.total_seconds() / divisor
    else:
        raise

Prevention

When it happens

Trigger: Dividing very large timedeltas by very small floats, e.g. `pd.to_timedelta(['100000d']) / 1e-9`, or `td_array / tiny_float_array`. Quotient in nanoseconds must exceed 2**63.

Common situations: Unit conversions that magnify values (days-to-nanoseconds via small divisors); accidental division by sub-second floats; mixing units in pipelines.

Related errors


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