pandas-dev/pandas · error · TypeError
cannot subtract a datelike from a {type(self).__name__}
Error message
cannot subtract a datelike from a {type(self).__name__} What it means
Raised by _sub_datetimelike_scalar when a datelike scalar (datetime/np.datetime64) is subtracted from an array whose dtype.kind is not 'M' (i.e., not a DatetimeArray). Subtracting a date from a TimedeltaArray or PeriodArray is not well-defined, so pandas raises TypeError rather than returning garbage.
Source
Thrown at pandas/core/arrays/datetimelike.py:1092
res_values = result.view(f"M8[{self.unit}]")
return DatetimeArray._simple_new(res_values, dtype=dtype)
@final
def _add_datetime_arraylike(self, other: DatetimeArray) -> DatetimeArray:
if not lib.is_np_dtype(self.dtype, "m"):
raise TypeError(
f"cannot add {type(self).__name__} and {type(other).__name__}"
)
# defer to DatetimeArray.__add__
return other + self
@final
def _sub_datetimelike_scalar(
self, other: datetime | np.datetime64
) -> TimedeltaArray:
if self.dtype.kind != "M":
raise TypeError(f"cannot subtract a datelike from a {type(self).__name__}")
self = cast("DatetimeArray", self)
# subtract a datetime from myself, yielding an ndarray[timedelta64[ns]]
if isna(other):
# i.e. np.datetime64("NaT")
return self - NaT
ts = Timestamp(other)
self, ts = self._ensure_matching_resos(ts)
return self._sub_datetimelike(ts)
@final
def _sub_datetime_arraylike(self, other: DatetimeArray) -> TimedeltaArray:
if self.dtype.kind != "M":
raise TypeError(f"cannot subtract a datelike from a {type(self).__name__}")
View on GitHub (pinned to 71959b8cb9)
Solutions
- Flip the operand order: pd.Timestamp('2020-01-01') - timedelta_idx yields a DatetimeIndex.
- If both operands are timestamps, ensure the left side is the DatetimeArray: use ts - td, not td - ts.
- For Period arrays, convert to timestamp first via idx.to_timestamp() if a datetime subtraction is intended.
- Inspect self.dtype.kind: only 'M' (datetime) supports subtracting a datelike scalar.
Example fix
// before
out = timedelta_idx - pd.Timestamp('2020-01-01') # TypeError
// after
out = pd.Timestamp('2020-01-01') - timedelta_idx Defensive patterns
Strategy: type-guard
Validate before calling
if idx.dtype.kind != 'M':
# subtracting a datetime scalar is invalid; flip the order
out = pd.Timestamp('2020-01-01') - idx
else:
out = idx - pd.Timestamp('2020-01-01') Type guard
def accepts_datelike_subtraction(idx) -> bool:
return getattr(idx.dtype, 'kind', None) == 'M' Try / catch
try:
out = idx - ts
except TypeError as e:
if 'cannot subtract a datelike' in str(e):
out = ts - idx
else:
raise Prevention
- Remember datetime - timedelta is valid; timedelta - datetime is not.
- Check left.dtype.kind == 'M' before subtracting a datelike scalar.
- Convert Period to timestamp if datetime subtraction is needed.
When it happens
Trigger: TimedeltaIndex - datetime, or PeriodIndex - datetime, dispatched through __sub__ line 1388 into _sub_datetimelike_scalar at line 1088; the guard at line 1091 fires.
Common situations: Subtracting the wrong operand order (datetime - timedelta is valid; timedelta - datetime is not), or assuming Period arithmetic accepts datetime.
Related errors
- cannot subtract {type(self).__name__} from {type(other).__na
- cannot subtract {type(self).__name__} from {type(other).__na
- overflow in timedelta operation
- cannot add {type(self).__name__} and {type(other).__name__}
- cannot subtract {type(self).__name__} from {other.dtype}
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/bf001520f8f349d9.
Report an issue: GitHub.