:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(endpoints): handle tz-aware datetime objects in materialized read (#58956)
Jovan Sakovic8c87dfe3f2b8
diff --git a/products/endpoints/backend/insight_transformers.py b/products/endpoints/backend/insight_transformers.pyindex 9a2f1c7a38f8..6fc8ab0a70b2 100644--- a/products/endpoints/backend/insight_transformers.py+++ b/products/endpoints/backend/insight_transformers.py@@ -114,26 +114,37 @@ def _extract_type_str(entry: Any) -> str | None:return None-def _parse_temporal_value(value: str, team_tz: "ZoneInfo | None") -> datetime:- """Parquet drops the timezone metadata from ClickHouse `DateTime('Europe/...')` columns,- so naive parsed values are treated as UTC and converted to team_tz before strftime.- Already-aware values are converted directly so the function is correct either way."""- parsed = datetime.fromisoformat(value)- if team_tz is not None:- if parsed.tzinfo is None:- parsed = parsed.replace(tzinfo=UTC)- parsed = parsed.astimezone(team_tz)- return parsed+def _to_team_tz(value: Any, team_tz: "ZoneInfo | None") -> Any:+ """Coerce a temporal value into something downstream ``strftime`` can render.++ ISO strings are always parsed to ``datetime`` so ``.strftime()`` calls don't blow up.+ When ``team_tz`` is given (DateTime columns), naive values are treated as UTC and+ converted to team_tz; aware values are converted directly. When ``team_tz`` is None+ (Date columns), the parsed value passes through unchanged. Non-temporal values pass+ through untouched.+ """+ if isinstance(value, str):+ parsed = datetime.fromisoformat(value)+ elif isinstance(value, datetime):+ parsed = value+ else:+ return value+ if team_tz is None:+ return parsed+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=UTC)+ return parsed.astimezone(team_tz)def _coerce_temporal_columns(rows: list, types: list | None, team: Team | None = None) -> None:- """Parse ISO strings into ``datetime`` objects for every Date/DateTime column.-- HogQL's response pipeline stringifies all Date/DateTime values regardless of name,- but the insight runners call .strftime() on them. We use the ``types`` metadata to- find temporal columns so this works for any column name (``date``, ``timestamp``,- custom aliases), not just ``date``. Rows can be tuples, so we replace the row in- the outer list.+ """Parse/coerce temporal values for every Date/DateTime column.++ For DateTime columns, ISO strings and tz-aware UTC datetimes are re-anchored to the+ team timezone so downstream strftime renders the correct local day. For Date columns+ (no tz conversion needed), string values are parsed to naive ``datetime`` objects so+ that downstream ``.strftime()`` calls succeed. We use the ``types`` metadata to find+ temporal columns so this works for any column name (``date``, ``timestamp``, custom+ aliases). Rows can be tuples, so we replace the row in the outer list."""if not types:return@@ -154,11 +165,9 @@ def _coerce_temporal_columns(rows: list, types: list | None, team: Team | None =value = row[col_idx]convert_tz = team_tz if is_datetime else Noneif isinstance(value, list):- coerced: Any = [- _parse_temporal_value(item, convert_tz) if isinstance(item, str) else item for item in value- ]- elif isinstance(value, str):- coerced = _parse_temporal_value(value, convert_tz)+ coerced: Any = [_to_team_tz(item, convert_tz) for item in value]+ elif isinstance(value, str | datetime):+ coerced = _to_team_tz(value, convert_tz)else:continueif new_row is None:diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.pyindex 0ca48a4e7232..17f892b60a91 100644--- a/products/endpoints/backend/tests/test_insight_response_parity.py+++ b/products/endpoints/backend/tests/test_insight_response_parity.py@@ -4,7 +4,7 @@ These tests are written TDD-style: they define the expected contract and initialmaterialized path currently returns flat HogQL data instead of rich insight-specific responses."""-from datetime import date+from datetime import UTC, date, datetimefrom typing import Anyimport pytest@@ -227,25 +227,43 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):)assert len(first["data"]) == 10, f"Expected 10 data points, got {len(first['data'])}"- # Each case picks parquet wall-clock UTC values that map to May 4/5/6 midnight in the- # team timezone — covers both UTC-ahead (Bucharest, prior day 21:00) and UTC-behind- # (New York, same day 04:00) offsets so the conversion direction is exercised both ways.+ # Cases cover both timezone-offset directions (UTC-ahead, UTC-behind) and both shapes+ # the materialized read can hand us (the CH Python client returns tz-aware UTC datetime+ # objects; ISO strings appear when results round-trip through JSON serialization).@parameterized.expand([(- "europe_bucharest",+ "europe_bucharest_str","Europe/Bucharest",["2026-05-03 21:00:00.000", "2026-05-04 21:00:00.000", "2026-05-05 21:00:00.000"],),(- "america_new_york",+ "europe_bucharest_aware_dt",+ "Europe/Bucharest",+ [+ datetime(2026, 5, 3, 21, 0, tzinfo=UTC),+ datetime(2026, 5, 4, 21, 0, tzinfo=UTC),+ datetime(2026, 5, 5, 21, 0, tzinfo=UTC),+ ],+ ),+ (+ "america_new_york_str","America/New_York",["2026-05-04 04:00:00.000", "2026-05-05 04:00:00.000", "2026-05-06 04:00:00.000"],),+ (+ "america_new_york_aware_dt",+ "America/New_York",+ [+ datetime(2026, 5, 4, 4, 0, tzinfo=UTC),+ datetime(2026, 5, 5, 4, 0, tzinfo=UTC),+ datetime(2026, 5, 6, 4, 0, tzinfo=UTC),+ ],+ ),])def test_transform_trends_formats_dates_in_team_timezone_at_day_boundary(- self, _name: str, team_timezone: str, parquet_date_strings: list[str]+ self, _name: str, team_timezone: str, date_values: list) -> None:self.team.timezone = team_timezoneself.team.save()@@ -255,10 +273,10 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):dateRange={"date_from": "2026-05-04", "date_to": "2026-05-06"},).model_dump()- # Shape matches what S3/parquet returns after round-trip: tz-stripped DateTime64- # values with millisecond precision.+ # Shape matches what the materialized read returns: a date column whose values+ # are either tz-aware UTC datetimes (CH Python client) or ISO strings (JSON path).result: dict[str, Any] = {- "results": [(0, parquet_date_strings, [1, 0, 2])],+ "results": [(0, date_values, [1, 0, 2])],"columns": ["__series_index", "date", "total"],"types": [["__series_index", "Int64"],@@ -274,6 +292,30 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):assert series["days"] == ["2026-05-04", "2026-05-05", "2026-05-06"]assert series["labels"] == ["4-May-2026", "5-May-2026", "6-May-2026"]+ def test_transform_trends_parses_date_column_strings_so_strftime_succeeds(self):+ """Date columns (no tz conversion) must still have ISO strings parsed to datetime+ objects — otherwise downstream strftime() raises AttributeError on the string."""+ original_query = TrendsQuery(+ series=[EventsNode(event="$pageview")],+ dateRange={"date_from": "2026-05-04", "date_to": "2026-05-06"},+ ).model_dump()++ result: dict[str, Any] = {+ "results": [(0, ["2026-05-04", "2026-05-05", "2026-05-06"], [1, 0, 2])],+ "columns": ["__series_index", "date", "total"],+ "types": [+ ["__series_index", "Int64"],+ ["date", "Array(Nullable(Date32))"],+ ["total", "Array(Nullable(UInt64))"],+ ],+ }++ _transform_trends(result, original_query, self.team)++ series = result["results"][0]+ assert series["days"] == ["2026-05-04", "2026-05-05", "2026-05-06"]+ assert series["labels"] == ["4-May-2026", "5-May-2026", "6-May-2026"]+# =========================================================================# LIFECYCLE# =========================================================================