pytest-dev/pytest · error · TypeError

absolute tolerance for datetime/timedelta must be a…

Error message

absolute tolerance for datetime/timedelta must be a timedelta, got {type(abs).__name__}

What it means

Raised by ApproxTimedelta.__init__ when abs is provided but is not a timedelta instance. datetime/timedelta comparisons require the absolute tolerance to be a timedelta so that arithmetic stays dimensionally consistent. Passing a number (int/float) or string is rejected with TypeError showing the actual type received.

Solutions

  1. Wrap the tolerance in timedelta: abs=timedelta(seconds=0.5).
  2. Use rel with a float if you want a proportional tolerance (timedelta only).
  3. Double-check the expected type is datetime/timedelta before using abs=timedelta(...).

Example fix

// before
approx(timedelta(seconds=10), abs=0.5)
// after
approx(timedelta(seconds=10), abs=timedelta(milliseconds=500))
Defensive patterns

Strategy: type-guard

Validate before calling

from datetime import timedelta
def approx_td(expected, *, abs=None, **kw):
    if abs is not None and not isinstance(abs, timedelta):
        raise TypeError('abs must be timedelta for time values')
    return approx(expected, abs=abs, **kw)

Type guard

from datetime import timedelta
def is_timedelta_or_none(v) -> bool:
    return v is None or isinstance(v, timedelta)

Prevention

When it happens

Trigger: approx(expected_timedelta, abs=0.5); approx(dt, abs=1); approx(td, abs='1s').

Common situations: Reusing scalar approx() muscle memory (where abs is a float) for time values; mixing tolerance units across assertion types.

Related errors


AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11). Data as JSON: /api/errors/d32b233972498213. Report an issue: GitHub.

Appendix: source

Thrown at src/_pytest/approx.py:664

        if isinstance(expected, datetime) and rel is not None:
            raise TypeError(
                "pytest.approx() does not support relative tolerance for "
                "datetime comparisons. Use abs=timedelta(...) instead."
            )
        if nan_ok:
            raise TypeError(
                "pytest.approx() does not support nan_ok for "
                "datetime/timedelta comparisons."
            )
        if abs is None and rel is None:
            raise TypeError(
                "pytest.approx() requires an explicit tolerance for "
                "datetime/timedelta comparisons: "
                "e.g. approx(expected, abs=timedelta(seconds=1)) "
                "or approx(expected, rel=0.01)"
            )
        if abs is not None and not isinstance(abs, timedelta):
            raise TypeError(
                f"absolute tolerance for datetime/timedelta must be a "
                f"timedelta, got {type(abs).__name__}"
            )
        if abs is not None and abs < timedelta(0):
            raise ValueError(f"absolute tolerance can't be negative: {abs}")
        if rel is not None:
            if not isinstance(rel, (int, float)):
                raise TypeError(
                    f"relative tolerance for timedelta must be a "
                    f"number, got {type(rel).__name__}"
                )
            if rel < 0:
                raise ValueError(f"relative tolerance can't be negative: {rel}")
            if math.isnan(rel):
                raise ValueError("relative tolerance can't be NaN.")
            if math.isinf(rel):
                raise ValueError("relative tolerance can't be infinite.")
        # Compute the effective tolerance. abs_tolerance is a timedelta, rel * expected

View on GitHub (pinned to 0d6fbdeffa)