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(hogql): parse zoned datetime strings compared to timestamps in python (#67603)

posthog[bot]4d291e33323d
diff --git a/posthog/hogql/helpers/test_timestamp_visitor.py b/posthog/hogql/helpers/test_timestamp_visitor.py
index d8a42d025fea..da1188a5d8e6 100644
--- a/posthog/hogql/helpers/test_timestamp_visitor.py
+++ b/posthog/hogql/helpers/test_timestamp_visitor.py
@@ -1,3 +1,5 @@
+from datetime import UTC, datetime, timedelta, timezone
+
import unittest
from parameterized import parameterized
@@ -17,6 +19,7 @@ from posthog.hogql.helpers.timestamp_visitor import (
is_start_of_day_constant,
is_start_of_hour_constant,
is_time_or_interval_constant,
+ parse_zoned_datetime_string,
)
@@ -584,3 +587,55 @@ class TestIsSimpleTimestampFieldExpression(unittest.TestCase):
ctx,
)
)
+
+
+class TestParseZonedDatetimeString(unittest.TestCase):
+ @parameterized.expand(
+ [
+ # Valid with an explicit timezone -> parsed to the exact instant.
+ (
+ "iso_utc_micros",
+ "2026-06-30T09:59:12.988000Z",
+ datetime(2026, 6, 30, 9, 59, 12, 988000, tzinfo=UTC),
+ ),
+ ("iso_utc_no_micros", "2026-06-30T09:59:12Z", datetime(2026, 6, 30, 9, 59, 12, tzinfo=UTC)),
+ ("space_sep_utc", "2026-06-30 09:59:12Z", datetime(2026, 6, 30, 9, 59, 12, tzinfo=UTC)),
+ (
+ "offset_with_colon",
+ "2026-06-30T09:59:12+02:00",
+ datetime(2026, 6, 30, 9, 59, 12, tzinfo=timezone(timedelta(hours=2))),
+ ),
+ (
+ "offset_no_colon",
+ "2026-06-30T09:59:12-0800",
+ datetime(2026, 6, 30, 9, 59, 12, tzinfo=timezone(timedelta(hours=-8))),
+ ),
+ (
+ "offset_with_micros",
+ "2026-06-30T09:59:12.5+02:00",
+ datetime(2026, 6, 30, 9, 59, 12, 500000, tzinfo=timezone(timedelta(hours=2))),
+ ),
+ (
+ "sub_microsecond_precision_truncated",
+ "2026-06-30T09:59:12.988000123Z",
+ datetime(2026, 6, 30, 9, 59, 12, 988000, tzinfo=UTC),
+ ),
+ # No timezone -> left for ClickHouse to interpret in the field timezone.
+ ("mysql_style", "2026-06-30 09:59:12", None),
+ ("iso_no_zone", "2026-06-30T09:59:12", None),
+ ("date_only", "2026-06-30", None),
+ ("with_micros_no_zone", "2026-06-30 09:59:12.988000", None),
+ # Looks zoned but is not a real datetime -> None, so the old clear error still surfaces.
+ ("month_out_of_range", "2026-13-45T99:99:99Z", None),
+ ("day_month_swapped", "2026-30-06T00:00:00Z", None),
+ ("impossible_offset", "2026-06-30T09:59:12+99:00", None),
+ ("overflows_timezone_conversion", "0001-01-01T00:00:00+14:00", None),
+ # Not a datetime at all.
+ ("arbitrary_string_ending_z", "some_value_Z", None),
+ ("empty", "", None),
+ ("non_string", 12345, None),
+ ("none", None, None),
+ ]
+ )
+ def test_parse_zoned_datetime_string(self, _name: str, value: object, expected: datetime | None) -> None:
+ self.assertEqual(parse_zoned_datetime_string(value), expected)
diff --git a/posthog/hogql/helpers/timestamp_visitor.py b/posthog/hogql/helpers/timestamp_visitor.py
index 8c4df56406be..694405a9ac85 100644
--- a/posthog/hogql/helpers/timestamp_visitor.py
+++ b/posthog/hogql/helpers/timestamp_visitor.py
@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
-from datetime import datetime
+from datetime import UTC, datetime
from typing import Optional
from posthog.hogql import ast
@@ -10,6 +10,24 @@ from posthog.hogql.errors import NotImplementedError
from posthog.hogql.visitor import Visitor
+def parse_zoned_datetime_string(value: object) -> Optional[datetime]:
+ """Parse a datetime string that has an explicit timezone ('Z' or an offset); None if naive or invalid."""
+ if not isinstance(value, str):
+ return None
+ try:
+ parsed = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ return None
+ try:
+ # Dates too close to datetime.min/max overflow when converted to another timezone.
+ parsed.astimezone(UTC)
+ except (OverflowError, ValueError):
+ return None
+ return parsed
+
+
def is_simple_timestamp_field_expression(
expr: ast.Expr, context: HogQLContext, tombstone_string: Optional[str] = None
) -> bool:
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index bf91590cbd94..61d63873a33c 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -16,6 +16,7 @@ from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_clickh
from posthog.hogql.functions import ADD_OR_NULL_DATETIME_FUNCTIONS, FIRST_ARG_DATETIME_FUNCTIONS
from posthog.hogql.functions.embed_text import resolve_embed_text
from posthog.hogql.functions.udfs import JSON_DROP_KEYS_CLICKHOUSE_NAME
+from posthog.hogql.helpers.timestamp_visitor import parse_zoned_datetime_string
from posthog.hogql.printer.base import BasePrinter, get_channel_definition_dict, resolve_field_type
from posthog.hogql.printer.hogql import HogQLPrinter
from posthog.hogql.restricted_properties import restricted_property_keys_for_table_type
@@ -83,6 +84,18 @@ COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING = {
# never be turned into an unparameterized read of arbitrary (e.g. user-supplied) text.
INLINE_SENTINEL_LITERALS = frozenset({"", "null", "true", "false", '^"|"$'})
+# Comparison ops where a datetime string with a timezone may be replaced by a datetime literal.
+ZONED_DATETIME_COERCIBLE_COMPARE_OPS = frozenset(
+ {
+ ast.CompareOperationOp.Eq,
+ ast.CompareOperationOp.NotEq,
+ ast.CompareOperationOp.Gt,
+ ast.CompareOperationOp.GtEq,
+ ast.CompareOperationOp.Lt,
+ ast.CompareOperationOp.LtEq,
+ }
+)
+
class ClickHousePrinter(BasePrinter):
DIALECT_NAME: ClassVar[HogQLDialect] = "clickhouse"
@@ -550,6 +563,19 @@ class ClickHousePrinter(BasePrinter):
return result
return []
+ @staticmethod
+ def _parse_zoned_datetime_constant(node: ast.Expr) -> datetime | None:
+ return parse_zoned_datetime_string(node.value) if isinstance(node, ast.Constant) else None
+
+ def _resolves_to_datetime(self, node: ast.Expr) -> bool:
+ if node.type is None:
+ return False
+ try:
+ constant_type = node.type.resolve_constant_type(self.context)
+ except Exception:
+ return False
+ return isinstance(constant_type, ast.DateTimeType)
+
def _is_events_table_timestamp_field(self, node: ast.Expr) -> bool:
traverser = GetFieldsTraverser(node)
@@ -618,6 +644,17 @@ class ClickHousePrinter(BasePrinter):
if any(col in left or col in right for col in COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING):
not_nullable = True
+ # ClickHouse can't parse datetime strings ending in 'Z' or an offset, so print those as datetime literals.
+ if node.op in ZONED_DATETIME_COERCIBLE_COMPARE_OPS:
+ if (
+ zoned_left := self._parse_zoned_datetime_constant(node.left)
+ ) is not None and self._resolves_to_datetime(node.right):
+ left = self._print_escaped_string(zoned_left)
+ elif (
+ zoned_right := self._parse_zoned_datetime_constant(node.right)
+ ) is not None and self._resolves_to_datetime(node.left):
+ right = self._print_escaped_string(zoned_right)
+
constant_lambda = None
value_if_one_side_is_null = False
value_if_both_sides_are_null = False
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index ce27d7218836..502a32d41142 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -2250,6 +2250,35 @@ class TestPrinter(BaseTest):
},
)
+ @parameterized.expand([("=",), ("!=",), (">",), ("<",), (">=",), ("<=",)])
+ def test_zoned_datetime_string_compared_to_timestamp_is_inlined_as_datetime(self, op: str):
+ # ClickHouse can't parse 'Z'/offset datetime strings, so they are parsed in Python and inlined.
+ printed = self._select(f"SELECT count() FROM events WHERE timestamp {op} '2026-06-30T09:59:12.988000Z'")
+ assert "toDateTime64('2026-06-30 09:59:12.988000', 6, 'UTC')" in printed, printed
+ assert "BestEffort" not in printed, printed
+
+ def test_zoned_datetime_string_instant_converted_to_team_timezone(self):
+ # The inlined literal must be the same instant converted to the team timezone.
+ self.team.timezone = "US/Pacific"
+ self.team.save()
+ printed = self._select("SELECT count() FROM events WHERE timestamp > '2026-06-30T09:59:12.988000Z'")
+ assert "toDateTime64('2026-06-30 02:59:12.988000', 6, 'US/Pacific')" in printed, printed
+
+ @parameterized.expand(
+ [
+ ("events", "timestamp = '2026-06-30 09:59:12'"), # no timezone, ClickHouse handles it
+ ("events", "timestamp = '2026-06-30'"),
+ ("events", "event = '2026-06-30T09:59:12.988000Z'"), # String column
+ ("events", "timestamp = '2026-30-06T00:00:00Z'"), # looks zoned but invalid, still errors loudly
+ ("exchange_rate", "date = '2026-06-30T09:59:12.988000Z'"), # Date column, left alone
+ ]
+ )
+ def test_datetime_string_comparison_stays_bare(self, table: str, where: str):
+ # Only valid timezone-carrying strings compared to DateTime fields get inlined.
+ printed = self._select(f"SELECT count() FROM {table} WHERE {where}")
+ assert "2026" not in printed, printed
+ assert "BestEffort" not in printed, printed
+
def test_print_timezone_gibberish(self):
self.team.timezone = "Europe/PostHogLandia"
self.team.save()
diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.py
index a5f060c038ce..a4d45ab9ca56 100644
--- a/posthog/hogql/transforms/property_types.py
+++ b/posthog/hogql/transforms/property_types.py
@@ -1,4 +1,3 @@
-import re
from datetime import datetime
from typing import Literal, Optional, cast
@@ -18,6 +17,7 @@ from posthog.hogql.database.schema.events import (
from posthog.hogql.database.schema.groups import GroupsTable
from posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable
from posthog.hogql.escape_sql import escape_hogql_identifier
+from posthog.hogql.helpers.timestamp_visitor import parse_zoned_datetime_string
from posthog.hogql.property_planner import PropertySourceKind, plan_property_access
from posthog.hogql.type_system import normalized_runtime_type, parse_sql_runtime_type
from posthog.hogql.visitor import CloningVisitor, TraversingVisitor
@@ -32,15 +32,6 @@ from posthog.clickhouse.materialized_columns import (
from posthog.models import Team
from posthog.models.property import PropertyName, TableColumn
-# ISO 8601 datetimes carrying a `T` date/time separator followed by a `Z`/±HH:MM
-# offset suffix. ClickHouse's toDateTime64 uses a strict parser that rejects these,
-# so they must go through parseDateTime64BestEffortOrNull instead.
-_ISO8601_WITH_OFFSET_RE = re.compile(r"\d{4}-\d{2}-\d{2}T.*(Z|[+-]\d{2}:?\d{2})")
-
-
-def _is_iso8601_with_offset(value: str) -> bool:
- return bool(_ISO8601_WITH_OFFSET_RE.fullmatch(value))
-
def build_property_swapper(node: ast.AST, context: HogQLContext) -> None:
from posthog.models import PropertyDefinition
@@ -527,22 +518,14 @@ class PropertySwapper(CloningVisitor):
if isinstance(inner, ast.Constant):
if isinstance(inner.value, datetime) and inner.value.tzinfo is not None:
return expr
- # ISO 8601 strings carrying a `T` separator followed by a `Z`/offset suffix
- # (e.g. '2026-05-18T00:00:00.000Z') are preserved upstream so the offset
- # can be honored (see property.py:_resolve_date_value). toDateTime64 uses
- # a strict parser that rejects the trailing `Z`, so route these through
- # HogQL's toDateTime, which lowers a string arg to
- # parseDateTime64BestEffortOrNull(str, 6, tz) and honors the offset.
- if isinstance(inner.value, str) and _is_iso8601_with_offset(inner.value):
- new_call = ast.Call(
- name="toDateTime",
- args=[inner, ast.Constant(value=tz)],
- )
- else:
- new_call = ast.Call(
- name="toDateTime64",
- args=[inner, ast.Constant(value=6), ast.Constant(value=tz)],
- )
+ # ClickHouse's toDateTime64 can't parse 'Z'/offset strings, so parse them in Python instead.
+ if (zoned := parse_zoned_datetime_string(inner.value)) is not None:
+ inner.value = zoned
+ return expr
+ new_call = ast.Call(
+ name="toDateTime64",
+ args=[inner, ast.Constant(value=6), ast.Constant(value=tz)],
+ )
if isinstance(expr, ast.Alias):
return ast.Alias(alias=expr.alias, expr=new_call)
return new_call