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.

chore(python): drop deprecated datetime.utcnow() (#60968)

Raúl Negrón-Otero51b654b128ba
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.py
index b00945cf3260..9ffa2162fc3b 100644
--- a/common/hogvm/python/stl/__init__.py
+++ b/common/hogvm/python/stl/__init__.py
@@ -456,7 +456,7 @@ def apply_interval_to_datetime(dt: dict, interval: dict) -> dict:
zone = dt["zone"] if is_hog_datetime(dt) else "UTC"
if is_hog_datetime(dt):
- base_dt = datetime.datetime.utcfromtimestamp(dt["dt"])
+ base_dt = datetime.datetime.fromtimestamp(dt["dt"], datetime.UTC).replace(tzinfo=None)
base_dt = pytz.timezone(zone).localize(base_dt)
else:
base_dt = datetime.datetime(dt["year"], dt["month"], dt["day"], tzinfo=pytz.timezone(zone))
@@ -544,7 +544,9 @@ def date_diff(args: list[Any], team: Optional["Team"], stdout: Optional[list[str
def to_dt(obj):
if is_hog_datetime(obj):
z = obj["zone"]
- return pytz.timezone(z).localize(datetime.datetime.utcfromtimestamp(obj["dt"]))
+ return pytz.timezone(z).localize(
+ datetime.datetime.fromtimestamp(obj["dt"], datetime.UTC).replace(tzinfo=None)
+ )
elif is_hog_date(obj):
return pytz.UTC.localize(datetime.datetime(obj["year"], obj["month"], obj["day"]))
else:
@@ -584,7 +586,7 @@ def date_trunc(args: list[Any], team: Optional["Team"], stdout: Optional[list[st
raise ValueError("Expected a DateTime for dateTrunc")
zone = dt["zone"]
- base_dt = datetime.datetime.utcfromtimestamp(dt["dt"])
+ base_dt = datetime.datetime.fromtimestamp(dt["dt"], datetime.UTC).replace(tzinfo=None)
base_dt = pytz.timezone(zone).localize(base_dt)
if unit == "year":
@@ -707,7 +709,9 @@ def extract(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]]
def to_dt(obj):
if is_hog_datetime(obj):
z = obj["zone"]
- return pytz.timezone(z).localize(datetime.datetime.utcfromtimestamp(obj["dt"]))
+ return pytz.timezone(z).localize(
+ datetime.datetime.fromtimestamp(obj["dt"], datetime.UTC).replace(tzinfo=None)
+ )
elif is_hog_date(obj):
return pytz.UTC.localize(datetime.datetime(obj["year"], obj["month"], obj["day"]))
else:
@@ -813,7 +817,7 @@ def toStartOfWeek(args: list[Any], team: Optional["Team"], stdout: Optional[list
dt = toDateTime(f"{dt['year']}-{dt['month']:02d}-{dt['day']:02d}")
else:
raise ValueError("Expected a Date or DateTime")
- base_dt = datetime.datetime.utcfromtimestamp(dt["dt"])
+ base_dt = datetime.datetime.fromtimestamp(dt["dt"], datetime.UTC).replace(tzinfo=None)
zone = dt["zone"]
base_dt = pytz.timezone(zone).localize(base_dt)
weekday = base_dt.isoweekday() # Monday=1, Sunday=7
diff --git a/ee/api/sentry_stats.py b/ee/api/sentry_stats.py
index b36b0b8a9172..13a042280d5d 100644
--- a/ee/api/sentry_stats.py
+++ b/ee/api/sentry_stats.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional, Union
from django.http import HttpRequest, JsonResponse
@@ -101,7 +101,7 @@ def get_stats_for_timerange(
@api_view(["GET"])
def sentry_stats(request: HttpRequest):
try:
- current_time = datetime.utcnow()
+ current_time = datetime.now(UTC)
target_end_date = current_time.strftime("%Y-%m-%dT%H:%M:%S")
target_start_date = (current_time - timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%S")
diff --git a/ee/tasks/auto_rollback_feature_flag.py b/ee/tasks/auto_rollback_feature_flag.py
index 2e18478ed64b..596257739d74 100644
--- a/ee/tasks/auto_rollback_feature_flag.py
+++ b/ee/tasks/auto_rollback_feature_flag.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
from celery import shared_task
@@ -70,7 +70,7 @@ def check_condition(rollback_condition: dict, feature_flag: FeatureFlag) -> bool
base_start_date = created_date.strftime("%Y-%m-%dT%H:%M:%S")
base_end_date = (created_date + timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%S")
- current_time = datetime.utcnow()
+ current_time = datetime.now(UTC)
target_end_date = current_time.strftime("%Y-%m-%dT%H:%M:%S")
target_start_date = (current_time - timedelta(days=1)).strftime("%Y-%m-%dT%H:%M:%S")
diff --git a/posthog/api/test/test_web_experiment.py b/posthog/api/test/test_web_experiment.py
index 0c21f162cd6c..8be9ccec9201 100644
--- a/posthog/api/test/test_web_experiment.py
+++ b/posthog/api/test/test_web_experiment.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, patch
@@ -117,8 +117,8 @@ class TestWebExperiment(APIBaseTest):
assert response.status_code == status.HTTP_201_CREATED, response_data
completed_web_exp_id = response_data["id"]
completed_web_exp = WebExperiment.objects.get(id=completed_web_exp_id)
- completed_web_exp.start_date = datetime.now().utcnow() - timedelta(days=2)
- completed_web_exp.end_date = datetime.now().utcnow()
+ completed_web_exp.start_date = datetime.now(UTC) - timedelta(days=2)
+ completed_web_exp.end_date = datetime.now(UTC)
completed_web_exp.save()
list_response = self.client.get(f"/api/web_experiments?token={self.team.api_token}")
assert list_response.status_code == status.HTTP_200_OK, list_response
diff --git a/posthog/session_recordings/queries/sub_queries/person_ids_subquery.py b/posthog/session_recordings/queries/sub_queries/person_ids_subquery.py
index 6a7792d64536..0c586d169ed9 100644
--- a/posthog/session_recordings/queries/sub_queries/person_ids_subquery.py
+++ b/posthog/session_recordings/queries/sub_queries/person_ids_subquery.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import UTC, datetime
from posthog.schema import RecordingsQuery
@@ -40,8 +40,8 @@ class PersonsIdCompareOperation(SessionRecordingsListingBaseQuery):
if not self._query.person_uuid:
return None
- # anchor to python now so that tests can freeze time
- now = datetime.utcnow()
+ # anchor to python now so that tests can freeze time; keep naive to match HogQL placeholder serialization
+ now = datetime.now(UTC).replace(tzinfo=None)
if poe_is_active(self._team):
return parse_select(
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index a935b8c1a671..f739a99bb6df 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -1,6 +1,6 @@
import re
from contextlib import nullcontext
-from datetime import datetime
+from datetime import UTC, datetime
from itertools import product
from typing import Literal
from uuid import uuid4
@@ -369,7 +369,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
keypress_count=2,
mouse_activity_count=2,
active_milliseconds=59000,
- kafka_timestamp=(datetime.utcnow() - relativedelta(minutes=6)),
+ kafka_timestamp=(datetime.now(UTC).replace(tzinfo=None) - relativedelta(minutes=6)),
)
produce_replay_summary(
@@ -383,7 +383,7 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
keypress_count=2,
mouse_activity_count=2,
active_milliseconds=61000,
- kafka_timestamp=(datetime.utcnow() - relativedelta(minutes=3)),
+ kafka_timestamp=(datetime.now(UTC).replace(tzinfo=None) - relativedelta(minutes=3)),
)
(session_recordings, _, _, _) = self._filter_recordings_by({})
diff --git a/posthog/session_recordings/queries/test/session_replay_sql.py b/posthog/session_recordings/queries/test/session_replay_sql.py
index f02465cae8dc..afbdcd9caada 100644
--- a/posthog/session_recordings/queries/test/session_replay_sql.py
+++ b/posthog/session_recordings/queries/test/session_replay_sql.py
@@ -1,4 +1,4 @@
-from datetime import datetime
+from datetime import UTC, datetime
from typing import Any, Optional
from uuid import uuid4
@@ -183,7 +183,7 @@ def produce_replay_summary(
if settings.TEST:
# we don't want to set _timestamp if we're using a real KafkaProducer
# and `ClickhouseProducer` does not use kafka when in test mode
- data["_timestamp"] = kafka_timestamp or datetime.utcnow().timestamp()
+ data["_timestamp"] = kafka_timestamp or datetime.now(UTC).timestamp()
p = ClickhouseProducer()
# because this is in a test it will write directly using SQL not really with Kafka
diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.py
index c07b81f06d1c..e77e0b045a23 100644
--- a/posthog/temporal/ai/posthog_code_slack_mention.py
+++ b/posthog/temporal/ai/posthog_code_slack_mention.py
@@ -3,7 +3,7 @@ import re
import json
import asyncio
from dataclasses import dataclass
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any, Literal
import structlog
@@ -1536,7 +1536,7 @@ def _extract_recent_assistant_text_from_logs(task_run: Any) -> str | None:
latest_text: str | None = None
latest_agent_timestamp: datetime | None = None
latest_user_timestamp: datetime | None = None
- cutoff = datetime.utcnow() - timedelta(minutes=5)
+ cutoff = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=5)
for line in log_content.strip().split("\n"):
line = line.strip()
diff --git a/posthog/temporal/proxy_service/monitor.py b/posthog/temporal/proxy_service/monitor.py
index 1b9ab6685a1d..db8f084f7125 100644
--- a/posthog/temporal/proxy_service/monitor.py
+++ b/posthog/temporal/proxy_service/monitor.py
@@ -276,7 +276,7 @@ async def check_proxy_is_live(inputs: CheckActivityInput) -> CheckActivityOutput
)
assert isinstance(cert["notAfter"], str)
expires_at = dt.datetime.strptime(cert["notAfter"], "%b %d %H:%M:%S %Y %Z")
- if expires_at - dt.datetime.utcnow() < dt.timedelta(days=14):
+ if expires_at - dt.datetime.now(dt.UTC).replace(tzinfo=None) < dt.timedelta(days=14):
return CheckActivityOutput(
errors=["Live proxy certificate is expiring soon"],
warnings=[],
diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.py
index 9a9cf44b7952..0821820a69f8 100644
--- a/products/exports/backend/temporal/subscriptions/activities.py
+++ b/products/exports/backend/temporal/subscriptions/activities.py
@@ -86,7 +86,7 @@ async def _persist_content_snapshot(
@temporalio.activity.defn
async def fetch_due_subscriptions_activity(inputs: FetchDueSubscriptionsActivityInputs) -> list[SubscriptionInfo]:
- now_with_buffer = dt.datetime.utcnow() + dt.timedelta(minutes=inputs.buffer_minutes)
+ now_with_buffer = dt.datetime.now(dt.UTC) + dt.timedelta(minutes=inputs.buffer_minutes)
await LOGGER.ainfo("Fetching due subscriptions", deadline=now_with_buffer)
@database_sync_to_async(thread_sensitive=False)
diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
index cba06b316a4b..4733b5d74131 100644
--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
@@ -1,5 +1,5 @@
import json
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any
from temporalio import activity
@@ -246,7 +246,7 @@ def _extract_recent_assistant_text_from_logs(task_run: Any) -> str | None:
return None
_AGENT_MSG_TYPES = {"agent_message", "agent_message_chunk"}
- cutoff = datetime.utcnow() - timedelta(minutes=5)
+ cutoff = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=5)
latest_user_timestamp: datetime | None = None
latest_agent_timestamp: datetime | None = None
@@ -336,7 +336,7 @@ def _has_recent_question_tool_failure(task_run: Any) -> bool:
if not log_content.strip():
return False
- cutoff = datetime.utcnow() - timedelta(minutes=5)
+ cutoff = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=5)
for line in log_content.strip().split("\n"):
line = line.strip()