{"record":{"id":"ee5f7a11a968c4d4","repo":"pandas-dev/pandas","slug":"cannot-subtract-type-self-name-from-other","errorCode":null,"errorMessage":"cannot subtract {type(self).__name__} from {other.dtype}","messagePattern":"cannot subtract (.+?) from (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":1458,"sourceCode":"            if lib.is_scalar(other):\n                # i.e. np.datetime64 object\n                return Timestamp(other) - self\n            if not isinstance(other, DatetimeLikeArrayMixin):\n                # Avoid down-casting DatetimeIndex\n                from pandas.core.arrays import DatetimeArray\n\n                other = DatetimeArray._from_sequence(other, dtype=other.dtype)\n            return other - self\n        elif self.dtype.kind == \"M\" and hasattr(other, \"dtype\") and not other_is_dt64:\n            # GH#19959 datetime - datetime is well-defined as timedelta,\n            # but any other type - datetime is not well-defined.\n            raise TypeError(\n                f\"cannot subtract {type(self).__name__} from \"\n                f\"{type(other).__name__}[{other.dtype}]\"\n            )\n        elif isinstance(self.dtype, PeriodDtype) and lib.is_np_dtype(other_dtype, \"m\"):\n            # TODO: Can we simplify/generalize these cases at all?\n            raise TypeError(f\"cannot subtract {type(self).__name__} from {other.dtype}\")\n        elif lib.is_np_dtype(self.dtype, \"m\"):\n            self = cast(\"TimedeltaArray\", self)\n            return (-self) + other\n\n        flipped = self - other\n        if flipped.dtype.kind == \"M\":\n            # GH#59571 give a more helpful exception message\n            raise TypeError(\n                f\"cannot subtract {type(self).__name__} from {type(other).__name__}\"\n            )\n        # We get here with e.g. datetime objects\n        return -flipped\n\n    def __iadd__(self, other) -> Self:\n        result = self + other\n        self[:] = result[:]\n        return self\n","sourceCodeStart":1440,"sourceCodeEnd":1476,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L1440-L1476","documentation":"Raised by __rsub__ when self.dtype is PeriodDtype and other has a timedelta (kind 'm') dtype. Subtracting a PeriodArray from a TimedeltaArray is not defined; the message reports other.dtype directly because the operation is only meaningful for PeriodArray - PeriodArray.","triggerScenarios":"timedelta_idx - period_idx, dispatched to __rsub__ at line 1431; the branch at line 1456 fires.","commonSituations":"Mixed Period/Timedelta arithmetic; assuming PeriodIndex participates in duration subtraction on either side.","solutions":["Convert the PeriodArray to Timestamps first: period_idx.to_timestamp(), then subtract.","Flip the operation: period_idx - timedelta shift is also unsupported; use idx.shift(n) instead.","Verify isinstance(left.dtype, pd.PeriodDtype) before performing reflected subtraction.","If a duration result is needed, work in ordinal space: period_idx.astype('int64')."],"exampleFix":"// before\nout = timedelta_idx - period_idx  # TypeError: cannot subtract PeriodArray from timedelta64[ns]\n// after\nout = period_idx.to_timestamp() - timedelta_idx","handlingStrategy":"type-guard","validationCode":"from pandas.api.types import is_period_dtype, is_timedelta64_dtype\nif is_period_dtype(idx.dtype) and is_timedelta64_dtype(getattr(other, 'dtype', None)):\n    raise TypeError('cannot subtract PeriodArray from TimedeltaIndex; convert first')","typeGuard":"def rejects_period_rsub_from_td(other, idx) -> bool:\n    from pandas.api.types import is_period_dtype, is_timedelta64_dtype\n    return is_period_dtype(idx.dtype) and is_timedelta64_dtype(getattr(other, 'dtype', None))","tryCatchPattern":"try:\n    out = timedelta_idx - period_idx\nexcept TypeError as e:\n    if 'cannot subtract' in str(e) and 'PeriodArray' in str(e):\n        out = period_idx.to_timestamp() - timedelta_idx\n    else:\n        raise","preventionTips":["Do not subtract PeriodArray from TimedeltaIndex; convert Period to timestamp.","Operate on Period arrays only with Period operands.","Validate both operand dtypes before mixed Period/Timedelta arithmetic."],"tags":["subtraction","rsub","period","timedelta"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}