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(insights): coerce date earliest_timestamp to datetime for month interval (#64966)

posthog[bot]bfb9ef174b2e
diff --git a/posthog/queries/test/test_util.py b/posthog/queries/test/test_util.py
index c7aa2bb5b4f9..b2d3cec18fb5 100644
--- a/posthog/queries/test/test_util.py
+++ b/posthog/queries/test/test_util.py
@@ -1,6 +1,12 @@
+from datetime import UTC, date, datetime
+
+from unittest.mock import patch
+
from django.test import TestCase
-from posthog.queries.util import correct_result_for_sampling
+from parameterized import parameterized
+
+from posthog.queries.util import correct_result_for_sampling, get_earliest_timestamp
class TestQueriesUtil(TestCase):
@@ -22,3 +28,21 @@ class TestQueriesUtil(TestCase):
res = correct_result_for_sampling(1, 0.01, "sum")
self.assertEqual(res, 100)
+
+ @parameterized.expand(
+ [
+ ("date", date(2024, 3, 21), datetime(2024, 3, 21, 0, 0, 0, tzinfo=UTC)),
+ (
+ "datetime_passthrough",
+ datetime(2024, 3, 21, 13, 45, 12, tzinfo=UTC),
+ datetime(2024, 3, 21, 13, 45, 12, tzinfo=UTC),
+ ),
+ ]
+ )
+ def test_get_earliest_timestamp_coerces_date_to_datetime(self, _name, returned, expected):
+ # ClickHouse may hand back a `date` for some teams; downstream interval alignment needs a `datetime`.
+ with patch("posthog.queries.util.insight_sync_execute", return_value=[[returned]]):
+ result = get_earliest_timestamp(1)
+
+ self.assertIsInstance(result, datetime)
+ self.assertEqual(result, expected)
diff --git a/posthog/queries/util.py b/posthog/queries/util.py
index ca6f45aa8e65..33c008057e8f 100644
--- a/posthog/queries/util.py
+++ b/posthog/queries/util.py
@@ -1,5 +1,5 @@
import json
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, date, datetime, time, timedelta
from enum import Enum, auto
from typing import Any, Optional, Union, overload
from zoneinfo import ZoneInfo
@@ -102,7 +102,12 @@ def get_earliest_timestamp(team_id: int) -> datetime:
)
if len(results) > 0:
- return results[0][0]
+ earliest = results[0][0]
+ # ClickHouse may return a `date` rather than a `datetime` for some teams' data; downstream
+ # interval alignment assumes a `datetime` (e.g. `datetime.date.replace` rejects time kwargs).
+ if isinstance(earliest, date) and not isinstance(earliest, datetime):
+ return datetime.combine(earliest, time.min, tzinfo=UTC)
+ return earliest
else:
return timezone.now() - DEFAULT_EARLIEST_TIME_DELTA