From 8639e1e23c0158803189c45d6028075ae6153b15 Mon Sep 17 00:00:00 2001 From: otiscuilei Date: Thu, 9 Jul 2026 03:36:11 +0800 Subject: [PATCH] fix: reconcile tz-aware and naive datetimes in ordering filters --- haystack/utils/filters.py | 2 ++ ...atetime-tz-aware-comparison-b2c3d4e5f6071829.yaml | 9 +++++++++ test/utils/test_filters.py | 12 ++++++++++++ 3 files changed, 23 insertions(+) create mode 100644 releasenotes/notes/filters-datetime-tz-aware-comparison-b2c3d4e5f6071829.yaml diff --git a/haystack/utils/filters.py b/haystack/utils/filters.py index 7443bcc14c9..7a7efbe77b6 100644 --- a/haystack/utils/filters.py +++ b/haystack/utils/filters.py @@ -63,6 +63,8 @@ def _prepare_ordering_comparison(value: Any, filter_value: Any) -> tuple[Any, An value = _parse_date(value) if not isinstance(filter_value, datetime): filter_value = _parse_date(filter_value) + + if isinstance(value, datetime) and isinstance(filter_value, datetime): value, filter_value = _ensure_both_dates_naive_or_aware(value, filter_value) if isinstance(filter_value, list): diff --git a/releasenotes/notes/filters-datetime-tz-aware-comparison-b2c3d4e5f6071829.yaml b/releasenotes/notes/filters-datetime-tz-aware-comparison-b2c3d4e5f6071829.yaml new file mode 100644 index 00000000000..40b291b2856 --- /dev/null +++ b/releasenotes/notes/filters-datetime-tz-aware-comparison-b2c3d4e5f6071829.yaml @@ -0,0 +1,9 @@ +--- +fixes: + - | + Fixed a ``TypeError`` raised when filtering documents with the ordering + operators (``>``, ``>=``, ``<``, ``<=``) where both the filter value and the + document meta value are ``datetime`` objects but one is timezone-aware and the + other is naive. The naive/aware reconciliation is now applied to any pair of + ``datetime`` operands, matching the behavior already used for ISO 8601 string + dates. diff --git a/test/utils/test_filters.py b/test/utils/test_filters.py index 777105a01dd..e34974dcc10 100644 --- a/test/utils/test_filters.py +++ b/test/utils/test_filters.py @@ -143,6 +143,18 @@ True, id="> operator with ISO 8601 string filter value and datetime Document value", ), + pytest.param( + {"field": "meta.date", "operator": ">", "value": datetime(2023, 1, 1, tzinfo=timezone.utc)}, + Document(meta={"date": datetime(2024, 1, 1)}), + True, + id="> operator with aware datetime filter value and naive datetime Document value", + ), + pytest.param( + {"field": "meta.date", "operator": ">", "value": datetime(2023, 1, 1)}, + Document(meta={"date": datetime(2024, 1, 1, tzinfo=timezone.utc)}), + True, + id="> operator with naive datetime filter value and aware datetime Document value", + ), pytest.param( {"field": "meta.page", "operator": ">", "value": 10}, Document(),