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.

feat(insights): day-of-week filtering for trends via DateRange.daysOfWeek (#68302)

Sam Pennington8cd1c681d689
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index a29ad7217c52..cd4eb7535def 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -17669,6 +17669,21 @@
"description": "End of the date range. Same format as date_from. Omit or null for \"now\".",
"type": ["string", "null"]
},
+ "daysOfWeek": {
+ "anyOf": [
+ {
+ "items": {
+ "enum": [1, 2, 3, 4, 5, 6, 7],
+ "type": "number"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries."
+ },
"explicitDate": {
"default": false,
"description": "Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period.",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 6ae13be8ff22..5528a748892c 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5104,6 +5104,12 @@ export interface DateRange {
* @default false
* */
explicitDate?: boolean | null
+ /**
+ * Restrict the query to events occurring on these ISO days of week
+ * (1=Monday to 7=Sunday), evaluated in the project timezone.
+ * Omit or empty for all days. Only applied by insight queries.
+ */
+ daysOfWeek?: (1 | 2 | 3 | 4 | 5 | 6 | 7)[] | null
}
export interface ResolvedDateRangeResponse {
diff --git a/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py b/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py
index ef134469dc3f..b1952fda365a 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py
@@ -9,13 +9,16 @@ from posthog.schema import (
BreakdownFilter,
BreakdownType,
DataWarehouseNode,
+ DateRange,
EventsNode,
MultipleBreakdownType,
PropertyMathType,
+ TrendsFilter,
TrendsQuery,
)
from posthog.hogql_queries.insights.trends.trend_validation_rules import (
+ DisallowDaysOfWeekWithSmoothing,
DisallowUnsupportedPropertyMathForHistogramBreakdown,
ValidateDataWarehouseBreakdown,
)
@@ -331,3 +334,38 @@ class TestDisallowUnsupportedPropertyMathForHistogramBreakdown(BaseTest):
DisallowUnsupportedPropertyMathForHistogramBreakdown().validate(self._context(query))
self.assertIn("Median is not supported", str(context.exception))
+
+
+class TestDisallowDaysOfWeekWithSmoothing(BaseTest):
+ def _context(self, query: TrendsQuery) -> QueryValidationContext[TrendsQuery]:
+ runner = MagicMock(query=query, team=self.team, user=None)
+ return QueryValidationContext(query=query, team=self.team, user=None, runner=runner)
+
+ @parameterized.expand(
+ [
+ ("smoothing_without_days_restriction", TrendsFilter(smoothingIntervals=7), None),
+ ("days_restriction_without_smoothing", None, [1, 2]),
+ ("smoothing_with_full_week", TrendsFilter(smoothingIntervals=7), [1, 2, 3, 4, 5, 6, 7]),
+ ("smoothing_interval_of_one", TrendsFilter(smoothingIntervals=1), [1, 2]),
+ ]
+ )
+ def test_allows(self, _name: str, trends_filter: TrendsFilter | None, days_of_week: list[int] | None) -> None:
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ trendsFilter=trends_filter,
+ dateRange=DateRange(daysOfWeek=days_of_week),
+ )
+
+ DisallowDaysOfWeekWithSmoothing().validate(self._context(query))
+
+ def test_disallows_smoothing_with_days_restriction(self) -> None:
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ trendsFilter=TrendsFilter(smoothingIntervals=7),
+ dateRange=DateRange(daysOfWeek=[1, 2, 3, 4, 5]),
+ )
+
+ with self.assertRaises(ValidationError) as context:
+ DisallowDaysOfWeekWithSmoothing().validate(self._context(query))
+
+ self.assertEqual(context.exception.get_codes(), ["days_of_week_unsupported_with_smoothing"])
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_persons.py b/posthog/hogql_queries/insights/trends/test/test_trends_persons.py
index 1e7e4af26d99..e81fd987a7cc 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trends_persons.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trends_persons.py
@@ -747,6 +747,36 @@ class TestTrendsPersons(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(get_distinct_id(result[2]), "person3")
self.assertEqual(get_event_count(result[2]), 1)
+ def test_trends_days_of_week_persons(self):
+ # The actors query must honor daysOfWeek like the trends query does, or the persons
+ # modal would list people whose only events fall on deselected days
+ _create_person(team_id=self.team.pk, distinct_ids=["person_weekend"], properties={})
+ _create_person(team_id=self.team.pk, distinct_ids=["person_weekday"], properties={})
+ _create_event(
+ event="$pageview",
+ distinct_id="person_weekend",
+ timestamp="2023-04-29 16:00", # Saturday
+ team=self.team,
+ )
+ _create_event(
+ event="$pageview",
+ distinct_id="person_weekday",
+ timestamp="2023-04-26 16:00", # Wednesday
+ team=self.team,
+ )
+
+ source_query = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ dateRange=DateRange(date_from="-7d", daysOfWeek=[6, 7]),
+ trendsFilter=TrendsFilter(display=ChartDisplayType.BOLD_NUMBER),
+ )
+
+ with freeze_time("2023-05-01T20:00:00.000Z"):
+ result = self._get_actors(trends_query=source_query)
+
+ self.assertEqual(len(result), 1)
+ self.assertEqual(get_distinct_id(result[0]), "person_weekend")
+
def test_trends_compare_persons(self):
self._create_events()
source_query = TrendsQuery(
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
index 76cf301bb056..c00dfe8cc418 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
@@ -55,6 +55,7 @@ from posthog.schema import (
TrendsFilter,
TrendsFormulaNode,
TrendsQuery,
+ TrendsQueryResponse,
)
from posthog.hogql import ast
@@ -526,6 +527,137 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(expected_days, response.results[0]["days"])
self.assertEqual(expected_data, response.results[0]["data"])
+ def _run_days_of_week_query(
+ self, interval: IntervalType, days_of_week: list[int], date_from: str, date_to: str
+ ) -> TrendsQueryResponse:
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ dateRange=DateRange(date_from=date_from, date_to=date_to, daysOfWeek=days_of_week),
+ interval=interval,
+ )
+ return TrendsQueryRunner(team=self.team, query=query).calculate()
+
+ def test_days_of_week_filters_events_and_day_buckets(self):
+ # 2020-01-06 is a Monday
+ self._create_events(
+ [
+ SeriesTestData(
+ distinct_id="p1",
+ events=[
+ Series(
+ event="$pageview",
+ timestamps=[
+ "2020-01-06T12:00:00Z", # Monday
+ "2020-01-07T12:00:00Z", # Tuesday
+ "2020-01-11T12:00:00Z", # Saturday
+ ],
+ )
+ ],
+ properties={},
+ )
+ ]
+ )
+
+ response = self._run_days_of_week_query(IntervalType.DAY, [1, 2], "2020-01-06", "2020-01-12")
+
+ self.assertEqual(["2020-01-06", "2020-01-07"], response.results[0]["days"])
+ self.assertEqual([1, 1], response.results[0]["data"])
+ self.assertEqual(2, response.results[0]["count"])
+
+ def test_days_of_week_restricts_events_within_longer_buckets(self):
+ self._create_events(
+ [
+ SeriesTestData(
+ distinct_id="p1",
+ events=[
+ Series(
+ event="$pageview",
+ timestamps=[
+ "2020-01-11T12:00:00Z", # Saturday
+ "2020-01-12T12:00:00Z", # Sunday
+ "2020-01-15T12:00:00Z", # Wednesday
+ "2020-02-08T12:00:00Z", # Saturday
+ ],
+ )
+ ],
+ properties={},
+ )
+ ]
+ )
+
+ response = self._run_days_of_week_query(IntervalType.MONTH, [6, 7], "2020-01-01", "2020-02-29")
+
+ self.assertEqual(["2020-01-01", "2020-02-01"], response.results[0]["days"])
+ self.assertEqual([2, 1], response.results[0]["data"])
+
+ def test_days_of_week_uses_project_timezone(self):
+ self.team.timezone = "US/Pacific"
+ self.team.save()
+ self._create_events(
+ [
+ SeriesTestData(
+ distinct_id="p1",
+ events=[
+ # 06:00 UTC Sunday = 22:00 Saturday in US/Pacific
+ Series(event="$pageview", timestamps=["2020-01-12T06:00:00Z"]),
+ ],
+ properties={},
+ )
+ ]
+ )
+
+ response = self._run_days_of_week_query(IntervalType.DAY, [6], "2020-01-06", "2020-01-12")
+
+ self.assertEqual(1, response.results[0]["count"])
+ self.assertEqual(["2020-01-11"], response.results[0]["days"])
+
+ def test_days_of_week_wau_counts_only_monday_events(self):
+ # p1 fires on Mon Jan 13 and Tue Jan 14 — only the Monday event counts with daysOfWeek=[1]
+ self._create_events(
+ [
+ SeriesTestData(
+ distinct_id="p1",
+ events=[
+ Series(
+ event="$pageview",
+ timestamps=[
+ "2020-01-13T12:00:00Z", # Monday — counted in WAU
+ "2020-01-14T12:00:00Z", # Tuesday — filtered out of aggregation
+ ],
+ )
+ ],
+ properties={},
+ )
+ ]
+ )
+ flush_persons_and_events()
+
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview", math=BaseMathType.WEEKLY_ACTIVE)],
+ dateRange=DateRange(date_from="2020-01-13", date_to="2020-01-20", daysOfWeek=[1]),
+ interval=IntervalType.DAY,
+ )
+ response = TrendsQueryRunner(team=self.team, query=query).calculate()
+
+ # With interval=day and daysOfWeek=[1], non-Monday buckets are removed from the response.
+ # Jan 13 WAU window [Jan 7–13] includes p1's Monday event → count=1.
+ # Jan 20 WAU window [Jan 14–20] has no Monday events (Tue Jan 14 is filtered) → count=0.
+ assert response.results[0]["days"] == ["2020-01-13", "2020-01-20"]
+ assert response.results[0]["data"] == [1, 0]
+
+ def test_days_of_week_with_smoothing_is_rejected(self):
+ # Smoothing would average the excluded days in as zeros; the runner must refuse the
+ # combination instead of returning silently understated values
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview")],
+ dateRange=DateRange(date_from="2020-01-06", date_to="2020-01-12", daysOfWeek=[1, 2]),
+ interval=IntervalType.DAY,
+ trendsFilter=TrendsFilter(smoothingIntervals=7),
+ )
+
+ with self.assertRaises(DRFValidationError):
+ TrendsQueryRunner(team=self.team, query=query).calculate()
+
def test_trends_days(self):
self._create_test_events()
diff --git a/posthog/hogql_queries/insights/trends/trend_validation_rules.py b/posthog/hogql_queries/insights/trends/trend_validation_rules.py
index 16dfe7f3ac33..3e84a3a103bf 100644
--- a/posthog/hogql_queries/insights/trends/trend_validation_rules.py
+++ b/posthog/hogql_queries/insights/trends/trend_validation_rules.py
@@ -87,3 +87,24 @@ class DisallowUnsupportedPropertyMathForHistogramBreakdown:
"Use average instead, or turn off binning on the breakdown.",
code=self.code,
)
+
+
+class DisallowDaysOfWeekWithSmoothing:
+ """Smoothing averages over the full date axis, where days excluded by daysOfWeek are structural zeros."""
+
+ code = "days_of_week_unsupported_with_smoothing"
+
+ def validate(self, context: QueryValidationContext[TrendsQuery]) -> None:
+ query = context.query
+ trends_filter = query.trendsFilter
+ if trends_filter is None or trends_filter.smoothingIntervals is None or trends_filter.smoothingIntervals <= 1:
+ return
+
+ days = set(query.dateRange.daysOfWeek or []) if query.dateRange else set()
+ if days and len(days) < 7:
+ raise ValidationError(
+ "Smoothing is not supported together with a days-of-week restriction: "
+ "the rolling average would count the excluded days as zeros and understate every value. "
+ "Remove smoothing or the daysOfWeek filter.",
+ code=self.code,
+ )
diff --git a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
index b18c95248316..32cc644b227d 100644
--- a/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
+++ b/posthog/hogql_queries/insights/trends/trends_actors_query_builder.py
@@ -311,6 +311,7 @@ class TrendsActorsQueryBuilder:
*self._entity_where_expr(),
*self._prop_where_expr(),
*(self._date_where_expr() if with_date_range_expr else []),
+ *self._day_of_week_where_expr(),
*(self._breakdown_where_expr() if with_breakdown_expr else []),
*self._filter_empty_actors_expr(),
]
@@ -321,6 +322,12 @@ class TrendsActorsQueryBuilder:
return ast.And(exprs=exprs)
return None
+ def _day_of_week_where_expr(self) -> list[ast.Expr]:
+ # Applied unconditionally (like in TrendsQueryBuilder) so the actors list matches the
+ # chart's counts even for multi-day buckets and total-value/active-user aggregations
+ day_of_week_filter = self.trends_date_range.day_of_week_filter_expr(ast.Field(chain=["timestamp"]))
+ return [day_of_week_filter] if day_of_week_filter is not None else []
+
def _ratio_expr(self) -> ast.RatioExpr | None:
if self.trends_query.samplingFactor is None:
return None
diff --git a/posthog/hogql_queries/insights/trends/trends_query_builder.py b/posthog/hogql_queries/insights/trends/trends_query_builder.py
index 207a52aba116..2a28ddc409c7 100644
--- a/posthog/hogql_queries/insights/trends/trends_query_builder.py
+++ b/posthog/hogql_queries/insights/trends/trends_query_builder.py
@@ -813,6 +813,10 @@ class TrendsQueryBuilder(DataWarehouseInsightQueryMixin):
]
)
+ day_of_week_filter = self.query_date_range.day_of_week_filter_expr(ast.Field(chain=["timestamp"]))
+ if day_of_week_filter is not None:
+ filters.append(day_of_week_filter)
+
# Filter by event or action name
if not self._aggregation_operation.is_first_time_ever_math():
event_or_action = self._event_or_action_where_expr()
diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.py
index db344fadd895..83121a00346c 100644
--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py
@@ -1,7 +1,7 @@
import threading
from collections.abc import Sequence
from copy import deepcopy
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
from math import ceil
from operator import itemgetter
from typing import Any, Optional, Union
@@ -58,6 +58,7 @@ from posthog.clickhouse.query_tagging import QueryTags
from posthog.hogql_queries.insights.trends.display import TrendsDisplay
from posthog.hogql_queries.insights.trends.series_with_extras import SeriesWithExtras
from posthog.hogql_queries.insights.trends.trend_validation_rules import (
+ DisallowDaysOfWeekWithSmoothing,
DisallowUnsupportedPropertyMathForHistogramBreakdown,
ValidateDataWarehouseBreakdown,
)
@@ -155,6 +156,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
DisallowUnsupportedDataWarehouseSettings(),
ValidateDataWarehouseBreakdown(),
DisallowUnsupportedPropertyMathForHistogramBreakdown(),
+ DisallowDaysOfWeekWithSmoothing(),
)
def _refresh_frequency(self):
@@ -537,12 +539,22 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
# weekend date buckets from the response so the chart x-axis shows weekdays.
# For week and longer intervals we keep all buckets since they span multiple days.
# For hour/minute intervals we skip bucket removal to avoid discarding all data on weekends.
+ allowed_days: Optional[set[int]] = None
if (
self.query.trendsFilter
and self.query.trendsFilter.hideWeekends
and self.query_date_range.interval_name not in ("hour", "minute", "week", "month", "quarter", "year")
):
- final_result = self._filter_weekend_buckets(final_result)
+ allowed_days = {1, 2, 3, 4, 5}
+
+ # daysOfWeek filters events at the query level; for day interval also drop the
+ # deselected day buckets so the chart doesn't show a row of zeros for them
+ days_of_week = self.query_date_range.days_of_week()
+ if days_of_week and self.query_date_range.interval_name == "day":
+ allowed_days = set(days_of_week) if allowed_days is None else allowed_days & set(days_of_week)
+
+ if allowed_days is not None:
+ final_result = self._filter_buckets_to_days(final_result, allowed_days)
return final_result, has_more
@@ -724,7 +736,21 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
res.append(series_object)
return res
- def _filter_weekend_buckets(self, results: list[dict]) -> list[dict]:
+ def _filter_buckets_to_days(self, results: list[dict], allowed_iso_days: set[int]) -> list[dict]:
+ # All series in a response usually share the same days axis, so cache the kept
+ # indices per axis instead of re-parsing every date string for every series
+ kept_indices_by_axis: dict[tuple, list[int]] = {}
+
+ def compute_kept_indices(days: list) -> list[int]:
+ kept_indices = []
+ for i, day_str in enumerate(days):
+ try:
+ if date.fromisoformat(day_str[:10]).isoweekday() in allowed_iso_days:
+ kept_indices.append(i)
+ except (ValueError, TypeError):
+ kept_indices.append(i) # Keep unparseable entries
+ return kept_indices
+
filtered = []
for series_result in results:
days = series_result.get("days")
@@ -732,29 +758,24 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
filtered.append(series_result)
continue
- # Build weekday mask — parse date string and check day of week
- weekday_indices = []
- for i, day_str in enumerate(days):
- try:
- dt = datetime.strptime(day_str[:10], "%Y-%m-%d")
- if dt.weekday() < 5: # Mon=0..Fri=4
- weekday_indices.append(i)
- except (ValueError, TypeError):
- weekday_indices.append(i) # Keep unparseable entries
+ axis = tuple(days)
+ kept_indices = kept_indices_by_axis.get(axis)
+ if kept_indices is None:
+ kept_indices = compute_kept_indices(days)
+ kept_indices_by_axis[axis] = kept_indices
- if len(weekday_indices) == len(days):
- # No weekends found, nothing to filter
+ if len(kept_indices) == len(days):
filtered.append(series_result)
continue
new_result = {**series_result}
- new_result["days"] = [days[i] for i in weekday_indices]
+ new_result["days"] = [days[i] for i in kept_indices]
if "data" in new_result and isinstance(new_result["data"], list):
- new_result["data"] = [new_result["data"][i] for i in weekday_indices]
+ new_result["data"] = [new_result["data"][i] for i in kept_indices]
if "labels" in new_result and isinstance(new_result["labels"], list):
- new_result["labels"] = [new_result["labels"][i] for i in weekday_indices]
+ new_result["labels"] = [new_result["labels"][i] for i in kept_indices]
# Recompute count from filtered data
if "data" in new_result and new_result.get("count") is not None:
@@ -770,7 +791,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
if new_result.get("action") is not None and "days" in new_result["action"]:
action_days = new_result["action"]["days"]
new_result["action"] = {**new_result["action"]}
- new_result["action"]["days"] = [d for d in action_days if d.weekday() < 5]
+ new_result["action"]["days"] = [d for d in action_days if d.isoweekday() in allowed_iso_days]
filtered.append(new_result)
return filtered
diff --git a/posthog/hogql_queries/utils/query_date_range.py b/posthog/hogql_queries/utils/query_date_range.py
index 8c0f74b946d5..ed934f5366d8 100644
--- a/posthog/hogql_queries/utils/query_date_range.py
+++ b/posthog/hogql_queries/utils/query_date_range.py
@@ -213,6 +213,34 @@ class QueryDateRange:
start += delta
return values
+ def days_of_week(self) -> Optional[list[int]]:
+ # Returns None for unset, empty input, or all seven days; all three mean "no restriction".
+ # The schema constrains values to 1..7, so no range validation is needed here.
+ days = self._date_range.daysOfWeek if self._date_range else None
+ if not days:
+ return None
+ valid_days = sorted({int(day) for day in days})
+ if len(valid_days) == 7:
+ return None
+ return valid_days
+
+ def day_of_week_filter_expr(self, timestamp_field: ast.Expr) -> Optional[ast.Expr]:
+ """`toDayOfWeek(ts, 0) IN (...)`, where mode 0 is ISO (1=Mon...7=Sun).
+
+ No explicit timezone argument: the HogQL property-type transform wraps DateTime fields
+ in `toTimeZone(..., <project tz>)`, so the day boundary follows the project timezone and
+ stays consistent with interval bucketing, including when the convertToProjectTimezone
+ modifier switches everything to UTC.
+ """
+ days = self.days_of_week()
+ if days is None:
+ return None
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Call(name="toDayOfWeek", args=[timestamp_field, ast.Constant(value=0)]),
+ right=ast.Tuple(exprs=[ast.Constant(value=day) for day in days]),
+ )
+
def date_to_as_hogql(self) -> ast.Expr:
return ast.Call(
name="assumeNotNull",
diff --git a/posthog/hogql_queries/utils/test/test_query_date_range.py b/posthog/hogql_queries/utils/test/test_query_date_range.py
index ce75b4a9f809..e3ebe4700ba4 100644
--- a/posthog/hogql_queries/utils/test/test_query_date_range.py
+++ b/posthog/hogql_queries/utils/test/test_query_date_range.py
@@ -1,10 +1,12 @@
from datetime import timedelta
+from typing import Optional
from zoneinfo import ZoneInfo
from posthog.test.base import APIBaseTest
from dateutil import parser
from parameterized import parameterized
+from pydantic import ValidationError as PydanticValidationError
from posthog.schema import DateRange, IntervalType
@@ -492,6 +494,34 @@ class TestDateFromAll(APIBaseTest):
self.assertEqual(qdr.date_from(), fallback)
+class TestDaysOfWeek(APIBaseTest):
+ def _make_qdr(self, days_of_week: Optional[list[int]]) -> QueryDateRange:
+ now = parser.isoparse("2021-08-25T00:00:00.000Z")
+ date_range = DateRange(date_from="-7d", daysOfWeek=days_of_week)
+ return QueryDateRange(team=self.team, date_range=date_range, interval=IntervalType.DAY, now=now)
+
+ @parameterized.expand(
+ [
+ ("field_unset", None, None),
+ ("empty_list", [], None),
+ ("full_week", [1, 2, 3, 4, 5, 6, 7], None),
+ ("valid_subset_sorted_deduped", [5, 1, 5], [1, 5]),
+ ]
+ )
+ def test_days_of_week_normalization(self, _name: str, days_of_week: Optional[list[int]], expected) -> None:
+ self.assertEqual(self._make_qdr(days_of_week).days_of_week(), expected)
+
+ @parameterized.expand([("zero_js_sunday_convention", [0]), ("out_of_range", [8])])
+ def test_days_of_week_out_of_range_rejected_by_schema(self, _name: str, days_of_week: list[int]) -> None:
+ with self.assertRaises(PydanticValidationError):
+ DateRange(date_from="-7d", daysOfWeek=days_of_week)
+
+ def test_days_of_week_unset_date_range_returns_none(self) -> None:
+ now = parser.isoparse("2021-08-25T00:00:00.000Z")
+ qdr = QueryDateRange(team=self.team, date_range=None, interval=IntervalType.DAY, now=now)
+ self.assertIsNone(qdr.days_of_week())
+
+
class TestQueryDateRangeWithIntervals(APIBaseTest):
def setUp(self):
self.now = parser.isoparse("2021-08-25T00:00:00.000Z")
diff --git a/posthog/schema.py b/posthog/schema.py
index 44ead9866bc4..d3e8289f512f 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -71,6 +71,7 @@ from posthog.schema_enums import (
DataTableNodeViewPropsContextType as DataTableNodeViewPropsContextType,
DataWarehouseSavedQueryOrigin as DataWarehouseSavedQueryOrigin,
DataWarehouseSourceCategory as DataWarehouseSourceCategory,
+ DaysOfWeekEnum as DaysOfWeekEnum,
DeepResearchType as DeepResearchType,
DefaultChannelTypes as DefaultChannelTypes,
DetailedResultsAggregationType as DetailedResultsAggregationType,
@@ -1001,6 +1002,14 @@ class DateRange(BaseModel):
default=None,
description=('End of the date range. Same format as date_from. Omit or null for "now".'),
)
+ daysOfWeek: list[DaysOfWeekEnum] | None = Field(
+ default=None,
+ description=(
+ "Restrict the query to events occurring on these ISO days of week (1=Monday"
+ " to 7=Sunday), evaluated in the project timezone. Omit or empty for all"
+ " days. Only applied by insight queries."
+ ),
+ )
explicitDate: bool | None = Field(
default=False,
description=(
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 0dad2ddaa1dd..06d64c46d7a1 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -884,6 +884,16 @@ class DatabaseSerializedFieldType(StrEnum):
UNKNOWN = "unknown"
+class DaysOfWeekEnum(float, Enum):
+ NUMBER_1 = 1
+ NUMBER_2 = 2
+ NUMBER_3 = 3
+ NUMBER_4 = 4
+ NUMBER_5 = 5
+ NUMBER_6 = 6
+ NUMBER_7 = 7
+
+
class DeepResearchType(StrEnum):
PLANNING = "planning"
REPORT = "report"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index e78526865d42..8ddd607721cc 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -972,12 +972,26 @@ export interface CustomEventConversionGoalApi {
customEventName: string
}
+export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]
+
+export const DaysOfWeekEnumApi = {
+ Number1: 1,
+ Number2: 2,
+ Number3: 3,
+ Number4: 4,
+ Number5: 5,
+ Number6: 6,
+ Number7: 7,
+} as const
+
export interface DateRangeApi {
/** Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),
* -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year). */
date_from?: string | null
/** End of the date range. Same format as date_from. Omit or null for "now". */
date_to?: string | null
+ /** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */
+ daysOfWeek?: DaysOfWeekEnumApi[] | null
/** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */
explicitDate?: boolean | null
}
diff --git a/products/product_analytics/backend/models/test/test_insight_model.py b/products/product_analytics/backend/models/test/test_insight_model.py
index 54e65eec04c5..40d60736927c 100644
--- a/products/product_analytics/backend/models/test/test_insight_model.py
+++ b/products/product_analytics/backend/models/test/test_insight_model.py
@@ -147,7 +147,12 @@ class TestInsightModel(BaseTest):
{},
{"date_from": "-14d", "date_to": "-7d"},
{
- "dateRange": {"date_from": "-14d", "date_to": "-7d", "explicitDate": False},
+ "dateRange": {
+ "date_from": "-14d",
+ "date_to": "-7d",
+ "explicitDate": False,
+ "daysOfWeek": None,
+ },
"filterTestAccounts": None,
"properties": None,
},
@@ -157,7 +162,12 @@ class TestInsightModel(BaseTest):
{"dateRange": {"date_from": "-2d", "date_to": "-1d"}},
{"date_from": "-4d", "date_to": "-3d"},
{
- "dateRange": {"date_from": "-4d", "date_to": "-3d", "explicitDate": False},
+ "dateRange": {
+ "date_from": "-4d",
+ "date_to": "-3d",
+ "explicitDate": False,
+ "daysOfWeek": None,
+ },
"filterTestAccounts": None,
"properties": None,
},
@@ -167,7 +177,12 @@ class TestInsightModel(BaseTest):
{"dateRange": {"date_from": "-14d", "date_to": "-7d"}},
{"date_from": "all"},
{
- "dateRange": {"date_from": "all", "date_to": None, "explicitDate": False},
+ "dateRange": {
+ "date_from": "all",
+ "date_to": None,
+ "explicitDate": False,
+ "daysOfWeek": None,
+ },
"filterTestAccounts": None,
"properties": None,
},
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index f7977b35ff79..9bdef6212857 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -286,12 +286,26 @@ export interface CustomEventConversionGoalApi {
customEventName: string
}
+export type DaysOfWeekEnumApi = (typeof DaysOfWeekEnumApi)[keyof typeof DaysOfWeekEnumApi]
+
+export const DaysOfWeekEnumApi = {
+ Number1: 1,
+ Number2: 2,
+ Number3: 3,
+ Number4: 4,
+ Number5: 5,
+ Number6: 6,
+ Number7: 7,
+} as const
+
export interface DateRangeApi {
/** Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),
* -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year). */
date_from?: string | null
/** End of the date range. Same format as date_from. Omit or null for "now". */
date_to?: string | null
+ /** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */
+ daysOfWeek?: DaysOfWeekEnumApi[] | null
/** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */
explicitDate?: boolean | null
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b3105b0d6d8a..e19745386027 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2354,12 +2354,27 @@ export namespace Schemas {
customEventName: string;
}
+ export type DaysOfWeekEnum = typeof DaysOfWeekEnum[keyof typeof DaysOfWeekEnum];
+
+
+ export const DaysOfWeekEnum = {
+ Number1: 1,
+ Number2: 2,
+ Number3: 3,
+ Number4: 4,
+ Number5: 5,
+ Number6: 6,
+ Number7: 7,
+ } as const;
+
export interface DateRange {
/** Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z) or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),
* -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year). */
date_from?: string | null;
/** End of the date range. Same format as date_from. Omit or null for "now". */
date_to?: string | null;
+ /** Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries. */
+ daysOfWeek?: DaysOfWeekEnum[] | null;
/** Whether the date_from and date_to should be used verbatim. Disables rounding to the start and end of period. */
explicitDate?: boolean | null;
}
diff --git a/services/mcp/src/tools/generated/mcp_analytics.ts b/services/mcp/src/tools/generated/mcp_analytics.ts
index 99de8d98f690..ad7311eb4159 100644
--- a/services/mcp/src/tools/generated/mcp_analytics.ts
+++ b/services/mcp/src/tools/generated/mcp_analytics.ts
@@ -217,6 +217,25 @@ const DateRange = z.object({
.nullable()
.describe('End of the date range. Same format as date_from. Omit or null for "now".')
.optional(),
+ daysOfWeek: z
+ .union([
+ z.array(
+ z.union([
+ z.literal(1),
+ z.literal(2),
+ z.literal(3),
+ z.literal(4),
+ z.literal(5),
+ z.literal(6),
+ z.literal(7),
+ ])
+ ),
+ z.null(),
+ ])
+ .describe(
+ 'Restrict the query to events occurring on these ISO days of week (1=Monday to 7=Sunday), evaluated in the project timezone. Omit or empty for all days. Only applied by insight queries.'
+ )
+ .optional(),
explicitDate: z.coerce
.boolean()
.nullable()