{"record":{"id":"ebf3801ff4760837","repo":"pandas-dev/pandas","slug":"cannot-add-or-subtract-timedelta64-ns-dtype-from","errorCode":null,"errorMessage":"Cannot add or subtract timedelta64[ns] dtype from {self.dtype}","messagePattern":"Cannot add or subtract timedelta64\\[ns\\] dtype from (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/period.py","lineNumber":1268,"sourceCode":"        else:\n            td = np.asarray(Timedelta(other).asm8)\n        return self._add_timedelta_arraylike(td)\n\n    def _add_timedelta_arraylike(\n        self, other: TimedeltaArray | npt.NDArray[np.timedelta64]\n    ) -> Self:\n        \"\"\"\n        Parameters\n        ----------\n        other : TimedeltaArray or ndarray[timedelta64]\n\n        Returns\n        -------\n        PeriodArray\n        \"\"\"\n        if not self.dtype._is_tick_like():\n            # We cannot add timedelta-like to non-tick PeriodArray\n            raise TypeError(\n                f\"Cannot add or subtract timedelta64[ns] dtype from {self.dtype}\"\n            )\n\n        dtype = np.dtype(f\"m8[{self.dtype._td64_unit}]\")\n\n        # Similar to _check_timedeltalike_freq_compat, but we raise with a\n        #  more specific exception message if necessary.\n        try:\n            delta = astype_overflowsafe(\n                np.asarray(other), dtype=dtype, copy=False, round_ok=False\n            )\n        except ValueError as err:\n            # e.g. if we have minutes freq and try to add 30s\n            # \"Cannot losslessly convert units\"\n            raise IncompatibleFrequency(\n                \"Cannot add/subtract timedelta-like from PeriodArray that is \"\n                \"not an integer multiple of the PeriodArray's freq.\"\n            ) from err","sourceCodeStart":1250,"sourceCodeEnd":1286,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/period.py#L1250-L1286","documentation":"Raised by PeriodArray._time_shift (the timedelta add/subtract path) when self.dtype._is_tick_like() is False. Only tick-like periods (second, minute, hour, day and their multiples) have a direct, unambiguous timedelta64 unit; higher-level periods (week, month, quarter, year) have variable lengths, so adding a raw timedelta64[ns] is undefined and rejected. The dtype is shown in the message.","triggerScenarios":"yearly_idx + pd.Timedelta('1D'); monthly_idx - np.timedelta64(1, 'h'); pd.period_range('2023', freq='Y')[0] + pd.Timedelta(hours=1). Any +/- with a Timedelta/TimedeltaArray on a non-tick PeriodArray.","commonSituations":"Treating all period types as if they were fixed-length; porting datetime arithmetic to period arithmetic without accounting for variable-length periods; business-calendar code.","solutions":["Use integer offsets with the period's own freq: idx + 1 * idx.freq (shifts by one period).","Convert to tick-like via .asfreq('D'/'h'/...) before timedelta arithmetic, then convert back if needed.","Use Timestamp arithmetic (.to_timestamp()) if you truly need nanosecond-resolution deltas."],"exampleFix":"# before\nidx = pd.period_range('2023', periods=3, freq='Y')\nidx + pd.Timedelta('1D')  # raises\n\n# after\nidx + 1 * idx.freq          # shift by one year\n# or\nidx.asfreq('D') + pd.Timedelta('1D')","handlingStrategy":"type-guard","validationCode":"import pandas as pd\n\ndef shift_period(period_idx, delta):\n    if isinstance(delta, (pd.Timedelta,)) and not period_idx.dtype._is_tick_like():\n        # convert delta to a number of periods\n        return period_idx + (delta // period_idx.freq.base)\n    return period_idx + delta","typeGuard":"def is_tick_like_period(period_idx) -> bool:\n    return period_idx.dtype._is_tick_like()","tryCatchPattern":"try:\n    period_idx + delta\nexcept TypeError as e:\n    if 'Cannot add or subtract timedelta' in str(e):\n        period_idx.asfreq('D') + delta  # downgrade to tick-like\n    else:\n        raise","preventionTips":["For non-tick periods (month/quarter/year), shift by integer multiples of idx.freq.","Use .asfreq('D'/'h'/...) to convert to a tick-like period before timedelta arithmetic.","Use .to_timestamp() if you truly need nanosecond-resolution datetime arithmetic."],"tags":["pandas","period","arithmetic","timedelta","freq"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}