{"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":1467,"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":1449,"sourceCodeEnd":1485,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/datetimelike.py#L1449-L1485","documentation":"Raised in __rsub__ when self is a PeriodArray (PeriodDtype) and other is a numpy timedelta64. Subtracting a timedelta from a Period in the reflected direction is not defined the way it is for DatetimeArray, so pandas rejects it, reporting the PeriodArray type and the timedelta dtype.","triggerScenarios":"np.timedelta64(1,'D') - PeriodArray(...); timedelta64 Series - PeriodIndex; any reflected subtraction where a timedelta is on the left and a Period array on the right.","commonSituations":"Mixed Period/timedelta arithmetic in scheduling code; assuming Period + timedelta commutes the way datetime + timedelta does.","solutions":["Put the PeriodArray on the left: parr + timedelta or parr - timedelta are the supported directions.","Convert the PeriodArray to timestamps via .to_timestamp() if you need datetime+timedelta semantics.","Use Period arithmetic appropriate to the freq (e.g. shift by integer count of periods)."],"exampleFix":"// before\nres = np.timedelta64(1, 'D') - parr  # TypeError\n\n// after\nres = parr + np.timedelta64(1, 'D')","handlingStrategy":"type-guard","validationCode":"import pandas as pd, numpy as np\n\ndef rsub_period_safe(parr, other):\n    if isinstance(parr.dtype, pd.PeriodDtype) and pd.api.types.is_timedelta64_dtype(getattr(other, 'dtype', None)):\n        raise TypeError('timedelta - PeriodArray is undefined; reverse the operands')\n    return other - parr","typeGuard":"import pandas as pd\n\ndef is_period_array(a) -> bool:\n    return isinstance(getattr(a, 'dtype', None), pd.PeriodDtype)","tryCatchPattern":"try:\n    res = other - parr\nexcept TypeError as e:\n    if 'cannot subtract' in str(e) and 'Period' in str(e):\n        res = parr + other  # PeriodArray + timedelta is supported\n    else:\n        raise","preventionTips":["Put the PeriodArray on the left for Period+timedelta arithmetic.","Convert PeriodArray via .to_timestamp() when you need datetime semantics.","Avoid reflected subtraction with timedelta on the left of a PeriodArray."],"tags":["datetime","arithmetic","period","rsub","type-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}