Skip to content

fix: normalize SDK timestamps to UTC - #872

Merged
marandaneto merged 9 commits into
mainfrom
fix/normalize-utc-timestamps
Aug 14, 2026
Merged

fix: normalize SDK timestamps to UTC#872
marandaneto merged 9 commits into
mainfrom
fix/normalize-utc-timestamps

Conversation

@marandaneto

Copy link
Copy Markdown
Member

💡 Motivation and Context

SDK event timestamps could retain a non-UTC offset even when they represented the correct instant. Exception stack timestamps also added a Z suffix without first converting aware values to UTC. This made timestamp output inconsistent across capture paths and could describe the wrong instant for exception frames.

This change converts canonical SDK timestamps to UTC. Timezone-aware datetimes and parseable ISO timestamp strings preserve their instant and are serialized with a +00:00 offset. Recent naive datetimes still use the existing local-time heuristic before conversion. Older and future naive values continue to be treated as UTC, and unparseable timestamp strings remain unchanged. Datetime values inside event properties are not modified.

The v0 queue, v1 event conversion, request timestamps, and aware exception frame timestamps now use UTC consistently. The public group_identify and alias annotations now document their existing support for datetime and string timestamps.

💚 How did you test it?

  • uv run pytest -q posthog/test/test_utils.py posthog/test/test_client.py posthog/test/test_capture_v1.py posthog/test/test_exception_utils.py posthog/test/test_module.py posthog/test/test_request.py
  • uv run ruff format --check posthog/__init__.py posthog/args.py posthog/capture_v1.py posthog/client.py posthog/exception_utils.py posthog/utils.py posthog/test/test_capture_v1.py posthog/test/test_client.py posthog/test/test_exception_utils.py posthog/test/test_module.py posthog/test/test_request.py posthog/test/test_utils.py
  • uv run ruff check posthog/__init__.py posthog/args.py posthog/capture_v1.py posthog/client.py posthog/exception_utils.py posthog/utils.py posthog/test/test_capture_v1.py posthog/test/test_client.py posthog/test/test_exception_utils.py posthog/test/test_module.py posthog/test/test_request.py posthog/test/test_utils.py
  • uv run --with griffe python .github/scripts/check_public_api.py
  • uv run python -W error -c "import posthog"

Regression tests verify that +05:30 and +05:45 timestamps preserve their exact instant when converted to UTC, v0 and v1 capture paths emit UTC values, request timestamps have a zero offset, aware exception timestamps are converted before adding Z, future naive ISO strings are not treated as recent local time on a non-UTC host, module-level timestamp annotations accept datetime and string values, and event property datetimes remain untouched.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

A Pi agent used the PR and autoreview skills to prepare this change. The final committed branch was reviewed against origin/main. The review found that future naive strings could incorrectly use the local timezone, so the recency check was bounded and regression coverage was added before the final clean review. A public API check also identified the intentional annotation updates and confirmed that the existing posthog.client.guess_timezone alias remains available.

@marandanetomarandaneto self-assigned this Aug 14, 2026
@github-actions

github-actionsBot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-14 11:21:33 UTC
Duration: 256450ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
TestStatusDuration
Endpoint And Method.Targets V1 Endpoint518ms
Endpoint And Method.Does Not Use Legacy Endpoints510ms
Required Headers.Has Authorization Bearer Header511ms
Required Headers.Has Content Type Json510ms
Required Headers.Has Posthog Sdk Info Format510ms
Required Headers.Has Posthog Attempt Header510ms
Required Headers.Has Posthog Request Id510ms
Required Headers.Has Posthog Request Timestamp510ms
Required Headers.Has User Agent510ms
Body Format.Body Has Created At And Batch511ms
Body Format.No Api Key In Body511ms
Body Format.No Sent At In Body510ms
Event Format.Event Has Required Root Fields511ms
Event Format.Event Uuid Is Valid512ms
Event Format.Event Timestamp Is Rfc3339511ms
Event Format.Distinct Id Is String510ms
Event Format.Distinct Id At Root Not Properties511ms
Event Format.Custom Properties Preserved511ms
Event Format.Set Properties Preserved510ms
Event Format.Set Once Properties Preserved511ms
Event Format.Groups Properties Preserved511ms
Event Format.Sdk Generates Uuid If Not Provided510ms
Event Format.Event Has Required Root Fields Batch515ms
Event Format.Event Uuid Is Valid Batch513ms
Event Format.Event Timestamp Is Rfc3339 Batch514ms
Event Format.Distinct Id Is String Batch514ms
Event Format.Distinct Id At Root Not Properties Batch514ms
Event Format.Custom Properties Preserved Batch514ms
Event Format.Set Properties Preserved Batch514ms
Event Format.Set Once Properties Preserved Batch513ms
Event Format.Groups Properties Preserved Batch515ms
Event Format.Sdk Generates Uuid If Not Provided Batch514ms
Batch Behavior.Multiple Events In Single Batch517ms
Batch Behavior.Batch Envelope Smoke515ms
Batch Behavior.Flush With No Events Sends Nothing507ms
Batch Behavior.Flush At Triggers Batch1012ms
Batch Behavior.Created At Reflects Batch Creation Time511ms
Deduplication.Generates Unique Uuids518ms
Deduplication.Different Events Same Content Different Uuids513ms
Deduplication.Preserves Uuid On Retry6520ms
Deduplication.Preserves Timestamp On Retry6519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry6521ms
Deduplication.No Duplicate Events In Batch519ms
Header Behavior On Retry.Attempt Header Starts At One510ms
Header Behavior On Retry.Attempt Header Increments On Retry13527ms
Header Behavior On Retry.Request Id Preserved On Retry6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry6520ms
Response Format Validation.Success Response Has Uuid Keyed Results511ms
Response Format Validation.Success Response Has Ok For Each Event515ms
Response Format Validation.Success No Retry After When All Ok514ms
Response Format Validation.Success Retry After Present When Retry Events1517ms
Response Format Validation.Success No Retry After When Drop Only513ms
Response Format Validation.Response Echoes Request Id510ms
Retry Behavior.Retries On 4086516ms
Retry Behavior.Retries On 5006520ms
Retry Behavior.Retries On 5038523ms
Retry Behavior.Retries On 5046516ms
Retry Behavior.Retryable Errors Have Retry After3515ms
Retry Behavior.Respects Retry After On Retryable Error11518ms
Retry Behavior.Does Not Retry On 4002514ms
Retry Behavior.Does Not Retry On 4012514ms
Retry Behavior.Does Not Retry On 4022512ms
Retry Behavior.Does Not Retry On 4132514ms
Retry Behavior.Does Not Retry On 4152512ms
Retry Behavior.Non Retryable Errors Have No Retry After2513ms
Retry Behavior.Implements Backoff22538ms
Retry Behavior.Max Retries Respected22527ms
Partial Batch Handling.Handles 200 Full Success2513ms
Partial Batch Handling.Handles 200 With All Ok3519ms
Partial Batch Handling.Does Not Retry Dropped Events3514ms
Partial Batch Handling.Does Not Retry Limited Events3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry6522ms
Partial Batch Handling.Retries Only Retry Events From Partial6521ms
Partial Batch Handling.Partial Retry Preserves Uuids6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments6518ms
Partial Batch Handling.Partial Retry Request Id Preserved6522ms
Partial Batch Handling.Respects Retry After On Partial8518ms
Partial Batch Handling.Unknown Result Treated As Terminal3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry3518ms
Compression.Sends Gzip Content Encoding511ms
Compression.No Content Encoding When Disabled511ms
Compression.Compressed Body Is Decompressible511ms
Error Handling.Does Not Retry On Unknown 4Xx2513ms
Event Options.Cookieless Mode Override510ms
Event Options.Disable Skew Correction Override511ms
Event Options.Process Person Profile Override510ms
Event Options.Product Tour Id Override511ms
Event Options.Unset Options Omitted510ms
Event Options.Options Override In Batch514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties511ms
Geoip And Historical Migration.Historical Migration Set In Body510ms
Geoip And Historical Migration.Historical Migration Absent By Default510ms

Feature_Flags Tests

17/17 tests passed

View Details
TestStatusDuration
Request Payload.Request With Person Properties Device Id12ms
Request Payload.Flags Request Uses V2 Query Param11ms
Request Payload.Flags Request Hits Flags Path Not Decide10ms
Request Payload.Flags Request Omits Authorization Header11ms
Request Payload.Token In Flags Body Matches Init11ms
Request Payload.Groups Round Trip11ms
Request Payload.Groups Default To Empty Object11ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False11ms
Request Payload.Disable Geoip Omitted Defaults To False11ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key11ms
Request Lifecycle.No Flags Request On Init Alone4ms
Request Lifecycle.No Flags Request On Normal Capture511ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests15ms
Request Lifecycle.Mock Response Value Is Returned To Caller10ms
Retry Behavior.Retries Flags On 502314ms
Retry Behavior.Retries Flags On 504315ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event512ms

@marandaneto
marandaneto marked this pull request as ready for review August 14, 2026 09:35
@marandaneto
marandaneto requested a review from a team as a code ownerAugust 14, 2026 09:35
@greptile-apps

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "docs: clarify UTC timestamp changeset" | Re-trigger Greptile

@arnohillenarnohillen left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(created by claude code)

[arno's agent] Verified at 015688a: guess_timezone now converts aware datetimes to the UTC instant (never relabels), the 0 <= delta bound stops future naive values being stamped local, every emission path normalizes (v0 enqueue, v1 idempotent re-normalize, sent_at already UTC), and tests assert exact instants; 111/111 compliance green.

@arnohillen

Copy link
Copy Markdown

(created by claude code)

[arno's agent] On Python 3.10 fromisoformat rejects non-canonical forms like +0530 offsets that 3.11+ parses, so the same string is normalized to UTC on 3.11+ but passed through unchanged on 3.10; the fallback is safe but the version divergence is worth a comment or test.

@arnohillen

Copy link
Copy Markdown

(created by claude code)

[arno's agent] _normalize_timestamp also parses date-only strings like 2026-06-27 and emits midnight UTC, a new silent coercion that no test covers.

@marandaneto

Copy link
Copy Markdown
MemberAuthor

Addressed the Python-version divergence in 46e2adc: compact offsets such as +0530 are now canonicalized before datetime.fromisoformat, with a regression test verified on Python 3.10.

@marandaneto

Copy link
Copy Markdown
MemberAuthor

Addressed the date-only coercion in 46e2adc: canonical extended and basic date-only strings are now preserved unchanged rather than converted to midnight UTC, with regression coverage.

Comment threadposthog/utils.py Outdated
@veria-ai

veria-aiBot commented Aug 14, 2026

Copy link
Copy Markdown

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@marandaneto
marandaneto enabled auto-merge (squash) August 14, 2026 11:17
@marandaneto
marandaneto merged commit 6fc55b6 into mainAug 14, 2026
38 checks passed
@marandaneto
marandaneto deleted the fix/normalize-utc-timestamps branch August 14, 2026 11:22
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@marandaneto@arnohillen