: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(insights): show full previous period for weekly/monthly compare (#88832)
Sam Penningtonefc0b0d8dd99
diff --git a/posthog/hogql_queries/utils/query_previous_period_date_range.py b/posthog/hogql_queries/utils/query_previous_period_date_range.pyindex 87a585cd5299..56ac864a4f86 100644--- a/posthog/hogql_queries/utils/query_previous_period_date_range.py+++ b/posthog/hogql_queries/utils/query_previous_period_date_range.py@@ -1,12 +1,24 @@from datetime import datetime, timedeltafrom typing import Optional+from dateutil.relativedelta import relativedelta+from posthog.schema import DateRange, IntervalTypefrom posthog.hogql_queries.utils.query_date_range import DateRangeBounds, QueryDateRangefrom posthog.models.team import Teamfrom posthog.utils import get_compare_period_dates, relative_date_parse_with_delta_mapping+# Calendar-anchored ranges that run to now ("This week/month/quarter/year"). Their previous period+# is the full prior calendar unit, so the length is a calendar delta rather than a fixed span of+# days — months, quarters and years vary in length, so sizing by elapsed days can't express them.+_FULL_PREVIOUS_CALENDAR_UNITS = {+ "wStart": {"weeks": 1},+ "mStart": {"months": 1},+ "qStart": {"months": 3},+ "yStart": {"years": 1},+}+# Originally similar to posthog/queries/query_date_range.py but rewritten to be used in HogQL queriesclass QueryPreviousPeriodDateRange(QueryDateRange):@@ -58,10 +70,32 @@ class QueryPreviousPeriodDateRange(QueryDateRange):return delta_mappingreturn None+ def full_previous_calendar_period(self, current_period_date_from: datetime) -> Optional[DateRangeBounds]:+ """The full prior calendar unit for a "This week/month/quarter/year" range that runs to now.++ A partial current period (e.g. this month so far) is then charted against the complete+ previous one, matching how hour/minute day-anchored ranges already behave. The end is the+ moment before the current period starts and the start is one calendar unit before that, so+ months, quarters and years come back whole regardless of their varying lengths.+ """+ if not self._date_range or self._date_range.date_to:+ return None+ unit = _FULL_PREVIOUS_CALENDAR_UNITS.get(self._date_range.date_from) if self._date_range.date_from else None+ if unit is None:+ return None+ return DateRangeBounds(+ date_from=current_period_date_from - relativedelta(**unit), # type: ignore[arg-type]+ date_to=current_period_date_from - timedelta(microseconds=1),+ )+def dates(self) -> DateRangeBounds:current_period_date_from = super().date_from()current_period_date_to = super().date_to()+ full_previous = self.full_previous_calendar_period(current_period_date_from)+ if full_previous is not None:+ return full_previous+if self._date_range and self._date_range.date_from == "all":# "All time" starts at the earliest event, whose time of day is arbitrary, while# get_compare_period_dates ends the previous period at date_to's time of day. Those twodiff --git a/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py b/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.pyindex 944b4f1693f2..99e679cc214c 100644--- a/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py+++ b/posthog/hogql_queries/utils/test/test_query_previous_period_date_range.py@@ -84,6 +84,37 @@ class TestQueryPreviousPeriodDateRange(APIBaseTest):self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_from))self.assertEqual(query_date_range.date_to(), parser.isoparse(expected_to))+ @parameterized.expand(+ [+ # "This week/month/quarter/year" run to now, so the current period is partial. The previous+ # period is the full prior calendar unit (weekday/day-of-month aligned, complete), matching+ # how day-anchored hour/minute ranges already behave — not the trailing slice of it.+ ("this_week", "2021-08-25T12:34:00Z", "wStart", "2021-08-15T00:00:00Z", "2021-08-21T23:59:59.999999Z"),+ ("this_month", "2021-08-25T12:34:00Z", "mStart", "2021-07-01T00:00:00Z", "2021-07-31T23:59:59.999999Z"),+ # A shorter previous month must still come back whole: diff-in-days sizing can't express this.+ (+ "this_month_february",+ "2021-03-15T12:34:00Z",+ "mStart",+ "2021-02-01T00:00:00Z",+ "2021-02-28T23:59:59.999999Z",+ ),+ ("this_quarter", "2021-08-25T12:34:00Z", "qStart", "2021-04-01T00:00:00Z", "2021-06-30T23:59:59.999999Z"),+ ("this_year", "2021-08-25T12:34:00Z", "yStart", "2020-01-01T00:00:00Z", "2020-12-31T23:59:59.999999Z"),+ ]+ )+ def test_previous_period_for_calendar_anchored_range_is_full_prior_unit(+ self, _name: str, now: str, date_from: str, expected_from: str, expected_to: str+ ):+ query_date_range = QueryPreviousPeriodDateRange(+ team=self.team,+ date_range=DateRange(date_from=date_from),+ interval=IntervalType.DAY,+ now=parser.isoparse(now),+ )+ self.assertEqual(query_date_range.date_from(), parser.isoparse(expected_from))+ self.assertEqual(query_date_range.date_to(), parser.isoparse(expected_to))+def test_explicit_timezone_info_overrides_team_timezone(self):# The previous-period delta parsing used to read directly from# `self._team.timezone_info`, so a `timezone_info=UTC` override on the constructor