pandas-dev/pandas · error · TypeError

Cannot divide by

Error message

Cannot divide {type(other).__name__} by {type(self).__name__}

What it means

Raised in TimedeltaArray._scalar_divlike_op when the operation is a reversed true/floor division (rtruediv/rfloordiv) and the scalar operand is numeric rather than a timedelta. Dividing a plain number by a duration has no well-defined result in pandas' timedelta semantics, so it is rejected as TypeError. Timezone/timedelta-typed operands take the earlier Timedelta-dispatch branch instead.

Solutions

  1. Reverse the expression: divide the timedelta by the scalar instead, if that matches intent.
  2. If a 1/duration rate is genuinely needed, compute it in numeric space (e.g. `1.0 / td.dt.total_seconds()`).
  3. Reorder operands so the timedelta is the numerator.

Example fix

# before
5 / pd.to_timedelta([1, 2], unit='D')  # TypeError

# after (compute rate numerically)
1.0 / pd.to_timedelta([1, 2], unit='D').total_seconds()
Defensive patterns

Strategy: type-guard

Validate before calling

import numbers, numpy as np
from pandas import Timedelta

def is_reverse_div_valid(numerator, td_array) -> bool:
    # reverse div is only valid when numerator is itself timedelta-like
    return isinstance(numerator, (Timedelta, np.timedelta64))

Type guard

import numpy as np
from pandas import Timedelta

def can_rdiv_td(numerator) -> bool:
    return isinstance(numerator, (Timedelta, np.timedelta64))

Try / catch

try:
    result = number / td_array
except TypeError as e:
    if 'Cannot divide' in str(e):
        result = 1.0 / td_array.dt.total_seconds() * number
    else:
        raise

Prevention

When it happens

Trigger: `5 / pd.to_timedelta([1, 2], unit='D')`, or `10 // pd.Timedelta('1D')`-style reverse division of a scalar number by a timedelta array.

Common situations: Writing division expressions in the wrong operand order; expecting rate (1/time) semantics that pandas does not provide for scalar numerators.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/84308a04c927d1b7. Report an issue: GitHub.

Appendix: source

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

        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)

        else:
            # caller is responsible for checking lib.is_scalar(other)
            # assume other is numeric, otherwise numpy will raise

            if op in [roperator.rtruediv, roperator.rfloordiv]:
                raise TypeError(
                    f"Cannot divide {type(other).__name__} by {type(self).__name__}"
                )

            other = _exact_if_integral(other)
            if lib.is_float(other):
                # GH#43178: raise instead of silently saturating on overflow
                self._check_float_div_overflow(other)
            result = op(self._ndarray, other)
            return type(self)._simple_new(result, dtype=result.dtype)

    def _cast_divlike_op(self, other):
        if not hasattr(other, "dtype"):
            # e.g. list, tuple
            other = np.array(other)

        if len(other) != len(self):
            raise ValueError("Cannot divide vectors with unequal lengths")
        return other

View on GitHub (pinned to 3b7651241d)