pandas-dev/pandas · error · TypeError

cannot subtract from

Error message

cannot subtract {type(self).__name__} from {type(other).__name__}

What it means

Raised in __rsub__ (GH#59571) as a clearer follow-up message when the flipped subtraction `self - other` produced a result whose dtype kind is 'M' (datetime). This shape indicates `<something> - datetime` would have yielded datetimes, which is nonsensical — the original operation is rejected with both type names so the user can see the operand confusion.

Solutions

  1. Convert the left operand to a DatetimeArray via pd.to_datetime so the standard datetime - datetime path (-> timedelta) is taken.
  2. Reorder the operation so a DatetimeArray is on the left: dta - other.
  3. Inspect dtype(other): if it is object containing datetimes, call pd.to_datetime(other) first.

Example fix

// before
res = obj_dates - dta  # object array of datetimes - DatetimeArray -> TypeError

// after
import pandas as pd
res = pd.to_datetime(obj_dates) - dta  # DatetimeArray - DatetimeArray -> TimedeltaIndex
Defensive patterns

Strategy: validation

Validate before calling

import pandas as pd

def rsub_object_safe(other, dta):
    if hasattr(other, 'dtype') and other.dtype == object:
        other = pd.to_datetime(other)
    return other - dta

Type guard

import pandas as pd

def is_object_array_of_datetimes(a) -> bool:
    if getattr(a, 'dtype', None) != object:
        return False
    return pd.api.types.infer_dtype(a, skipna=True) in ('datetime', 'datetime64')

Try / catch

try:
    res = other - dta
except TypeError as e:
    if 'cannot subtract' in str(e):
        res = pd.to_datetime(other) - dta
    else:
        raise

Prevention

When it happens

Trigger: Subtracting a DatetimeArray from an object-dtype collection of datetimes that did not get inferred as datetimelike; e.g. list_of_datetimes - DatetimeIndex where the left stays object dtype and the flip yields datetime64.

Common situations: Reflected arithmetic with Python datetime objects held in an object array; user code that subtracts dates from non-date containers and gets a misleading datetime result.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/datetimelike.py:1475

            return other - self
        elif self.dtype.kind == "M" and hasattr(other, "dtype") and not other_is_dt64:
            # GH#19959 datetime - datetime is well-defined as timedelta,
            # but any other type - datetime is not well-defined.
            raise TypeError(
                f"cannot subtract {type(self).__name__} from "
                f"{type(other).__name__}[{other.dtype}]"
            )
        elif isinstance(self.dtype, PeriodDtype) and lib.is_np_dtype(other_dtype, "m"):
            # TODO: Can we simplify/generalize these cases at all?
            raise TypeError(f"cannot subtract {type(self).__name__} from {other.dtype}")
        elif lib.is_np_dtype(self.dtype, "m"):
            self = cast("TimedeltaArray", self)
            return (-self) + other

        flipped = self - other
        if flipped.dtype.kind == "M":
            # GH#59571 give a more helpful exception message
            raise TypeError(
                f"cannot subtract {type(self).__name__} from {type(other).__name__}"
            )
        # We get here with e.g. datetime objects
        return -flipped

    def __iadd__(self, other) -> Self:
        result = self + other
        self[:] = result[:]
        return self

    def __isub__(self, other) -> Self:
        result = self - other
        self[:] = result[:]
        return self

    # --------------------------------------------------------------
    # Reductions

View on GitHub (pinned to 3b7651241d)