reflex-dev/reflex · error · VarTypeError

Cannot compare a datetime object with a non-datetime object.

Error message

Cannot compare a datetime object with a non-datetime object.

What it means

DateTimeVar comparison operators (<, <=, >, >=) only work between two datetime/date vars; comparing a datetime var with anything else raises VarTypeError via this helper.

Source

Thrown at packages/reflex-base/src/reflex_base/vars/datetime.py:40

DATETIME_T = TypeVar("DATETIME_T", datetime, date)

datetime_types = datetime | date

_COMPARE_DATETIME_IMPORT = {
    "$/utils/helpers/datetime.js": [
        ImportVar(tag="compareDatetime", is_default=True, install=False)
    ],
}


def raise_var_type_error():
    """Raise a VarTypeError.

    Raises:
        VarTypeError: Cannot compare a datetime object with a non-datetime object.
    """
    msg = "Cannot compare a datetime object with a non-datetime object."
    raise VarTypeError(msg)


class DateTimeVar(Var[DATETIME_T], python_types=(datetime, date)):
    """A variable that holds a datetime or date object."""

    __hash__ = Var.__hash__

    def __eq__(self, other: Any) -> BooleanVar:
        """Equal comparison.

        Args:
            other: The other datetime to compare.

        Returns:
            The result of the comparison.
        """
        if not isinstance(other, DATETIME_TYPES):
            return super().__eq__(other)

View on GitHub (pinned to 45b8ed5ab7)

Solutions

  1. Convert the other side to a datetime: State.when < datetime(2024,1,1) or datetime.fromisoformat(...)
  2. Use .contains/other string ops for string comparisons instead of ordering comparisons

Example fix

# before
rx.cond(State.created_at < "2024-01-01", ...)
# after
from datetime import datetime
rx.cond(State.created_at < datetime(2024, 1, 1), ...)
Defensive patterns

Strategy: type-guard

Validate before calling

from datetime import datetime, date
assert isinstance(other, (datetime, date)), 'compare with datetime objects only'

Type guard

def is_date_like(v) -> bool:
    from datetime import datetime, date
    return isinstance(v, (datetime, date))

Prevention

When it happens

Trigger: State.when < 5, State.created_at < "2024-01-01" (plain string), or comparing a DateTimeVar to an int/str Var.

Common situations: Comparing a state datetime to a string date instead of parsing it first; mixing DateVar with number vars in conditions.

Related errors


AI-assisted analysis of reflex-dev/reflex@45b8ed5ab7 (2026-08-28). Data as JSON: /api/errors/40c3205fb9bb142d. Report an issue: GitHub.