Skip to content

: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.

fix(endpoints): preserve team timezone on materialized insight day buckets (#58891)

Jovan Sakovic3d1b97a10e9b
diff --git a/products/endpoints/backend/insight_transformers.py b/products/endpoints/backend/insight_transformers.py
index df6d4ffe12ed..9a2f1c7a38f8 100644
--- a/products/endpoints/backend/insight_transformers.py
+++ b/products/endpoints/backend/insight_transformers.py
@@ -8,8 +8,9 @@ that users expect (matching what the non-materialized path produces).
import re
from collections import defaultdict
-from datetime import datetime
+from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, Union, cast
+from zoneinfo import ZoneInfo
import structlog
@@ -91,6 +92,7 @@ def _strip_hogql_fields(result: dict) -> None:
_TEMPORAL_TYPE_RE = re.compile(r"\b(?:Date|DateTime|DateTime64|Date32)\b")
+_DATETIME_TYPE_RE = re.compile(r"\bDateTime(?:64)?\b")
def _is_temporal_type(type_str: str) -> bool:
@@ -98,6 +100,11 @@ def _is_temporal_type(type_str: str) -> bool:
return bool(_TEMPORAL_TYPE_RE.search(type_str))
+def _is_datetime_type(type_str: str) -> bool:
+ """True only for DateTime/DateTime64 (point-in-time), not Date/Date32 (calendar day)."""
+ return bool(_DATETIME_TYPE_RE.search(type_str))
+
+
def _extract_type_str(entry: Any) -> str | None:
"""Accept both `[[col_name, type_str], ...]` (real API) and `[type_str, ...]` (mocks)."""
if isinstance(entry, str):
@@ -107,7 +114,19 @@ def _extract_type_str(entry: Any) -> str | None:
return None
-def _coerce_temporal_columns(rows: list, types: list | None) -> 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 _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,
@@ -118,19 +137,28 @@ def _coerce_temporal_columns(rows: list, types: list | None) -> None:
"""
if not types:
return
- temporal_indices = [i for i, entry in enumerate(types) if (t := _extract_type_str(entry)) and _is_temporal_type(t)]
- if not temporal_indices:
+ temporal_cols: list[tuple[int, bool]] = []
+ for i, entry in enumerate(types):
+ type_str = _extract_type_str(entry)
+ if not type_str or not _is_temporal_type(type_str):
+ continue
+ temporal_cols.append((i, _is_datetime_type(type_str)))
+ if not temporal_cols:
return
+ team_tz: ZoneInfo | None = team.timezone_info if team is not None else None
for i, row in enumerate(rows):
new_row: list | None = None
- for col_idx in temporal_indices:
+ for col_idx, is_datetime in temporal_cols:
if col_idx >= len(row):
continue
value = row[col_idx]
+ convert_tz = team_tz if is_datetime else None
if isinstance(value, list):
- coerced: Any = [datetime.fromisoformat(item) if isinstance(item, str) else item for item in value]
+ coerced: Any = [
+ _parse_temporal_value(item, convert_tz) if isinstance(item, str) else item for item in value
+ ]
elif isinstance(value, str):
- coerced = datetime.fromisoformat(value)
+ coerced = _parse_temporal_value(value, convert_tz)
else:
continue
if new_row is None:
@@ -151,7 +179,7 @@ def _transform_trends(result: dict, original_query: dict, team: Team, now: datet
_strip_hogql_fields(result)
return
- _coerce_temporal_columns(rows, result.get("types"))
+ _coerce_temporal_columns(rows, result.get("types"), team)
series_index_col = columns.index("__series_index") if "__series_index" in columns else None
groups: dict[int, list] = defaultdict(list)
@@ -199,7 +227,7 @@ def _transform_lifecycle(result: dict, original_query: dict, team: Team, now: da
_strip_hogql_fields(result)
return
- _coerce_temporal_columns(rows, result.get("types"))
+ _coerce_temporal_columns(rows, result.get("types"), team)
response = HogQLQueryResponse(results=rows, columns=columns)
result["results"] = runner.format_results(response)
diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.py
index 70df2fb6ae06..0ca48a4e7232 100644
--- a/products/endpoints/backend/tests/test_insight_response_parity.py
+++ b/products/endpoints/backend/tests/test_insight_response_parity.py
@@ -5,6 +5,7 @@ materialized path currently returns flat HogQL data instead of rich insight-spec
"""
from datetime import date
+from typing import Any
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
@@ -12,6 +13,7 @@ from unittest import mock
from django.utils import timezone
+from parameterized import parameterized
from rest_framework import status
from posthog.schema import (
@@ -28,6 +30,7 @@ from posthog.schema import (
from products.data_warehouse.backend.models import DataWarehouseTable
from products.data_warehouse.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.endpoints.backend.insight_transformers import _transform_trends
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
pytestmark = [pytest.mark.django_db]
@@ -224,6 +227,53 @@ 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.
+ @parameterized.expand(
+ [
+ (
+ "europe_bucharest",
+ "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",
+ "America/New_York",
+ ["2026-05-04 04:00:00.000", "2026-05-05 04:00:00.000", "2026-05-06 04:00:00.000"],
+ ),
+ ]
+ )
+ def test_transform_trends_formats_dates_in_team_timezone_at_day_boundary(
+ self, _name: str, team_timezone: str, parquet_date_strings: list[str]
+ ) -> None:
+ self.team.timezone = team_timezone
+ self.team.save()
+
+ original_query = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ 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.
+ result: dict[str, Any] = {
+ "results": [(0, parquet_date_strings, [1, 0, 2])],
+ "columns": ["__series_index", "date", "total"],
+ "types": [
+ ["__series_index", "Int64"],
+ ["date", "Array(Nullable(DateTime64(3, 'UTC')))"],
+ ["total", "Array(Nullable(UInt64))"],
+ ],
+ }
+
+ _transform_trends(result, original_query, self.team)
+
+ series = result["results"][0]
+ assert series["data"] == [1, 0, 2]
+ 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
# =========================================================================