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.

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

github-actions Bot 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
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 518ms
Endpoint And Method.Does Not Use Legacy Endpoints 510ms
Required Headers.Has Authorization Bearer Header 511ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 510ms
Required Headers.Has Posthog Attempt Header 510ms
Required Headers.Has Posthog Request Id 510ms
Required Headers.Has Posthog Request Timestamp 510ms
Required Headers.Has User Agent 510ms
Body Format.Body Has Created At And Batch 511ms
Body Format.No Api Key In Body 511ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 511ms
Event Format.Event Uuid Is Valid 512ms
Event Format.Event Timestamp Is Rfc3339 511ms
Event Format.Distinct Id Is String 510ms
Event Format.Distinct Id At Root Not Properties 511ms
Event Format.Custom Properties Preserved 511ms
Event Format.Set Properties Preserved 510ms
Event Format.Set Once Properties Preserved 511ms
Event Format.Groups Properties Preserved 511ms
Event Format.Sdk Generates Uuid If Not Provided 510ms
Event Format.Event Has Required Root Fields Batch 515ms
Event Format.Event Uuid Is Valid Batch 513ms
Event Format.Event Timestamp Is Rfc3339 Batch 514ms
Event Format.Distinct Id Is String Batch 514ms
Event Format.Distinct Id At Root Not Properties Batch 514ms
Event Format.Custom Properties Preserved Batch 514ms
Event Format.Set Properties Preserved Batch 514ms
Event Format.Set Once Properties Preserved Batch 513ms
Event Format.Groups Properties Preserved Batch 515ms
Event Format.Sdk Generates Uuid If Not Provided Batch 514ms
Batch Behavior.Multiple Events In Single Batch 517ms
Batch Behavior.Batch Envelope Smoke 515ms
Batch Behavior.Flush With No Events Sends Nothing 507ms
Batch Behavior.Flush At Triggers Batch 1012ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 518ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6520ms
Deduplication.Preserves Timestamp On Retry 6519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6521ms
Deduplication.No Duplicate Events In Batch 519ms
Header Behavior On Retry.Attempt Header Starts At One 510ms
Header Behavior On Retry.Attempt Header Increments On Retry 13527ms
Header Behavior On Retry.Request Id Preserved On Retry 6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6520ms
Response Format Validation.Success Response Has Uuid Keyed Results 511ms
Response Format Validation.Success Response Has Ok For Each Event 515ms
Response Format Validation.Success No Retry After When All Ok 514ms
Response Format Validation.Success Retry After Present When Retry Events 1517ms
Response Format Validation.Success No Retry After When Drop Only 513ms
Response Format Validation.Response Echoes Request Id 510ms
Retry Behavior.Retries On 408 6516ms
Retry Behavior.Retries On 500 6520ms
Retry Behavior.Retries On 503 8523ms
Retry Behavior.Retries On 504 6516ms
Retry Behavior.Retryable Errors Have Retry After 3515ms
Retry Behavior.Respects Retry After On Retryable Error 11518ms
Retry Behavior.Does Not Retry On 400 2514ms
Retry Behavior.Does Not Retry On 401 2514ms
Retry Behavior.Does Not Retry On 402 2512ms
Retry Behavior.Does Not Retry On 413 2514ms
Retry Behavior.Does Not Retry On 415 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After 2513ms
Retry Behavior.Implements Backoff 22538ms
Retry Behavior.Max Retries Respected 22527ms
Partial Batch Handling.Handles 200 Full Success 2513ms
Partial Batch Handling.Handles 200 With All Ok 3519ms
Partial Batch Handling.Does Not Retry Dropped Events 3514ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6518ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6522ms
Partial Batch Handling.Retries Only Retry Events From Partial 6521ms
Partial Batch Handling.Partial Retry Preserves Uuids 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved 6522ms
Partial Batch Handling.Respects Retry After On Partial 8518ms
Partial Batch Handling.Unknown Result Treated As Terminal 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3518ms
Compression.Sends Gzip Content Encoding 511ms
Compression.No Content Encoding When Disabled 511ms
Compression.Compressed Body Is Decompressible 511ms
Error Handling.Does Not Retry On Unknown 4Xx 2513ms
Event Options.Cookieless Mode Override 510ms
Event Options.Disable Skew Correction Override 511ms
Event Options.Process Person Profile Override 510ms
Event Options.Product Tour Id Override 511ms
Event Options.Unset Options Omitted 510ms
Event Options.Options Override In Batch 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 511ms
Geoip And Historical Migration.Historical Migration Set In Body 510ms
Geoip And Historical Migration.Historical Migration Absent By Default 510ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 12ms
Request Payload.Flags Request Uses V2 Query Param 11ms
Request Payload.Flags Request Hits Flags Path Not Decide 10ms
Request Payload.Flags Request Omits Authorization Header 11ms
Request Payload.Token In Flags Body Matches Init 11ms
Request Payload.Groups Round Trip 11ms
Request Payload.Groups Default To Empty Object 11ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 11ms
Request Payload.Disable Geoip Omitted Defaults To False 11ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 11ms
Request Lifecycle.No Flags Request On Init Alone 4ms
Request Lifecycle.No Flags Request On Normal Capture 511ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 15ms
Request Lifecycle.Mock Response Value Is Returned To Caller 10ms
Retry Behavior.Retries Flags On 502 314ms
Retry Behavior.Retries Flags On 504 315ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 512ms

@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 owner August 14, 2026 09:35
@greptile-apps

greptile-apps Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

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

@arnohillen arnohillen 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
Member Author

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
Member Author

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 thread posthog/utils.py Outdated
@veria-ai

veria-ai Bot 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 main Aug 14, 2026
38 checks passed
@marandaneto
marandaneto deleted the fix/normalize-utc-timestamps branch August 14, 2026 11:22
Sign up for free to 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