pandas-dev/pandas · error · TypeError

cannot subtract from [ ]

Error message

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

What it means

Raised in __rsub__ when self.dtype.kind == 'M' (datetime) but the other operand has a dtype and is not datetimelike (other_is_dt64 is False). Pandas treats datetime - datetime as well-defined (-> timedelta), but `<other non-dt type> - datetime` is not, so the reflected subtraction is refused with a message naming both types and the other's dtype.

Solutions

  1. Reverse the operand order so the datetime is on the left: datetime - datetime -> timedelta, or datetime - timedelta -> datetime.
  2. If the left operand is numeric and represents offsets, convert it to timedelta first (pd.to_timedelta) before subtracting from a datetime.
  3. Cast or infer the other operand so it is recognized as datetimelike if that was the intent.

Example fix

// before
res = nums - dta  # nums is int64 -> TypeError

// after
res = dta - nums.astype('timedelta64[s]')  # or dta - pd.to_timedelta(nums, unit='s')
Defensive patterns

Strategy: type-guard

Validate before calling

import pandas as pd

def rsub_safe(dta, other):
    other_dt = getattr(other, 'dtype', None)
    if other_dt is not None and not pd.api.types.is_datetime64_any_dtype(other) and dta.dtype.kind == 'M':
        raise TypeError(f'cannot subtract {type(dta).__name__} from non-datetime {other_dt}')
    return other - dta

Type guard

import pandas as pd

def is_recognized_datetimelike(other) -> bool:
    d = getattr(other, 'dtype', None)
    if d is None:
        return False
    return d.kind in 'mM' or isinstance(d, pd.PeriodDtype)

Try / catch

try:
    res = other - dta
except TypeError as e:
    if 'cannot subtract' in str(e) and 'from' in str(e):
        res = dta - other  # reverse if a difference was intended
    else:
        raise

Prevention

When it happens

Trigger: np.array([1,2,3]) - DatetimeIndex(...); int Series - datetime Series; float64 array - DatetimeArray; object column minus a datetime column where inference did not classify it as datetimelike.

Common situations: Reflected arithmetic where the left operand is numeric/object and the right is a datetime column; subtraction order mistakes in elapsed-time calculations.

Related errors


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

Appendix: source

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

            other_dtype, DatetimeTZDtype
        )

        if other_is_dt64 and lib.is_np_dtype(self.dtype, "m"):
            # ndarray[datetime64] cannot be subtracted from self, so
            # we need to wrap in DatetimeArray/Index and flip the operation
            if lib.is_scalar(other):
                # i.e. np.datetime64 object
                return Timestamp(other) - self
            if not isinstance(other, DatetimeLikeArrayMixin):
                # Avoid down-casting DatetimeIndex
                from pandas.core.arrays import DatetimeArray

                other = DatetimeArray._from_sequence(other, dtype=other.dtype)
            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

View on GitHub (pinned to 3b7651241d)