pandas-dev/pandas · error · TypeError

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

Error message

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

What it means

Raised by TimedeltaArray._scalar_divlike_op for reverse true/floor division: dividing a non-timedelta scalar (numeric) by a timedelta is mathematically undefined in pandas' model, so a TypeError names both types. e.g. `5 / pd.Timedelta('1d')` is meaningless without a target unit.

Source

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

        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__}"
                )

            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 71959b8cb9)

Solutions

  1. Swap operand order: divide the timedelta by the scalar to get a scaled timedelta.
  2. If you want a count, divide the timedelta by another timedelta: `td_a / td_b`.
  3. For numeric output use .dt.total_seconds() then do ordinary division.

Example fix

// before
count = 5 / pd.Timedelta('2h')

// after
count = pd.Timedelta('10h') / pd.Timedelta('2h')  # -> 5.0
Defensive patterns

Strategy: type-guard

Validate before calling

import numbers
if isinstance(other, numbers.Number) and not hasattr(other, 'dtype'):
    # ensure divisor is the timedelta, not the dividend
    raise TypeError('reverse numeric/timedelta division is unsupported; swap operands')

Type guard

def is_valid_td_dividend(x) -> bool:
    import pandas as pd
    return isinstance(x, (pd.Timedelta, pd.TimedeltaIndex)) or (
        hasattr(x, 'dtype') and x.dtype.kind == 'm')

Try / catch

try:
    out = scalar / td
except TypeError as e:
    if 'Cannot divide' in str(e) and 'by' in str(e):
        out = td / scalar  # swap to forward op
    else:
        raise

Prevention

When it happens

Trigger: Calling `int / timedelta` or `float / timedelta`, or `int // timedelta_array`. Triggers in the reverse ops rtruediv/rfloordiv branch when other is a scalar not in _recognized_scalars.

Common situations: Confusing the operand order; trying to express 'how many periods fit in N' by dividing a count by a duration instead of the reverse.

Related errors


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