pandas-dev/pandas · error · TypeError

' ' with datetime64 dtypes is no longer supported. Use (obj…

Error message

'{how}' with datetime64 dtypes is no longer supported. Use (obj != pd.Timestamp(0)).{how}() instead.

What it means

Raised in _groupby_op (GH#34479) when dtype.kind == 'M' and `how` is 'any' or 'all'. Earlier pandas versions allowed these to implicitly coerce datetimes to truthiness; that behavior was removed because it was ambiguous, so the operation now raises and directs users to an explicit (obj != pd.Timestamp(0)).any()/all().

Solutions

  1. Make truthiness explicit: (df[date_col].notna()).any() or df.groupby('k')[date_col].apply(lambda s: s.notna().any()).
  2. Use the suggested form (obj != pd.Timestamp(0)).any()/all() if you need a non-zero reference.
  3. Run any/all on the notna mask of the datetime column rather than the column itself.

Example fix

// before
df.groupby('k')['timestamp'].any()  # TypeError after GH#34479

// after
df.assign(_has_ts=df['timestamp'].notna()).groupby('k')['_has_ts'].any()
Defensive patterns

Strategy: validation

Validate before calling

import pandas as pd

DT_TRUTH_OPS = {'any', 'all'}

def any_all_dt_safe(df, key, col, how):
    if df[col].dtype.kind == 'M' and how in DT_TRUTH_OPS:
        mask = df[col].notna()
        return getattr(df.assign(_m=mask).groupby(key)['_m'], how)()
    return getattr(df.groupby(key)[col], how)()

Type guard

import pandas as pd

def is_datetime64_series(s) -> bool:
    return getattr(s, 'dtype', None) is not None and s.dtype.kind == 'M'

Try / catch

try:
    return getattr(df.groupby('k')[date_col], how)()
except TypeError as e:
    if 'no longer supported' in str(e) and how in ('any', 'all'):
        mask = df[date_col].notna()
        return getattr(df.assign(_m=mask).groupby('k')['_m'], how)()
    raise

Prevention

When it happens

Trigger: df.groupby('k')[date_col].any(); .all() on a datetime64 column; groupby aggregations listing 'any'/'all' across heterogeneous columns including datetime.

Common situations: Upgrading pandas across the version that removed implicit datetime truthiness (GH#34479); generic 'is there any data' checks that call .any() on every column.

Related errors


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

Appendix: source

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

    def _groupby_op(
        self,
        *,
        how: str,
        has_dropped_na: bool,
        min_count: int,
        ngroups: int,
        ids: npt.NDArray[np.intp],
        **kwargs,
    ):
        dtype = self.dtype
        if dtype.kind == "M":
            # Adding/multiplying datetimes is not valid
            if how in ["sum", "prod", "cumsum", "cumprod", "var", "skew", "kurt"]:
                raise TypeError(f"datetime64 type does not support operation '{how}'")
            if how in ["any", "all"]:
                # GH#34479
                raise TypeError(
                    f"'{how}' with datetime64 dtypes is no longer supported. "
                    f"Use (obj != pd.Timestamp(0)).{how}() instead."
                )

        elif isinstance(dtype, PeriodDtype):
            # Adding/multiplying Periods is not valid
            if how in ["sum", "prod", "cumsum", "cumprod", "var", "skew", "kurt"]:
                raise TypeError(f"Period type does not support {how} operations")
            if how in ["any", "all"]:
                # GH#34479
                raise TypeError(
                    f"'{how}' with PeriodDtype is no longer supported. "
                    f"Use (obj != pd.Period(ordinal=0, freq=freq)).{how}() instead."
                )
        # timedeltas we can add but not multiply
        elif how in ["prod", "cumprod", "skew", "kurt", "var"]:
            raise TypeError(f"timedelta64 type does not support {how} operations")

View on GitHub (pinned to 3b7651241d)