Fix #1126: Fix microseconds lose on jwt.encode for known time claims#1127
Fix #1126: Fix microseconds lose on jwt.encode for known time claims#1127rodrigovillarbello wants to merge 2 commits intojpadilla:masterfrom
Conversation
for more information, see https://pre-commit.ci
auvipy
left a comment
There was a problem hiding this comment.
please also add proper test
There was a problem hiding this comment.
Pull request overview
This PR fixes issue #1126 by preserving microsecond precision when encoding datetime objects in JWT time claims (exp, iat, nbf). The change replaces timegm(utctimetuple()) with the native timestamp() method, which maintains the full precision of datetime objects.
Key changes:
- Replaced
timegm(payload[time_claim].utctimetuple())withpayload[time_claim].timestamp()for datetime conversion - Removed the unused
calendar.timegmimport - Updated the comment to reflect that datetimes are now converted to float values instead of integer values
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # Convert datetime to a float value in known time-format claims | ||
| if isinstance(payload.get(time_claim), datetime): | ||
| payload[time_claim] = timegm(payload[time_claim].utctimetuple()) | ||
| payload[time_claim] = payload[time_claim].timestamp() |
There was a problem hiding this comment.
The change from timegm(utctimetuple()) to timestamp() introduces a behavioral difference for naive datetime objects (datetimes without timezone information). The old implementation treated naive datetimes as UTC, while timestamp() treats them as local time. This could be a breaking change for users passing naive datetime objects. Consider adding validation to require timezone-aware datetime objects, or document this behavioral change clearly.
| # Convert datetime to a float value in known time-format claims | ||
| if isinstance(payload.get(time_claim), datetime): | ||
| payload[time_claim] = timegm(payload[time_claim].utctimetuple()) | ||
| payload[time_claim] = payload[time_claim].timestamp() |
There was a problem hiding this comment.
This change enables microsecond precision in timestamp encoding, but there's no test to verify this new behavior. Consider adding a test that encodes a datetime with microseconds and verifies that the microseconds are preserved in the decoded payload. For example, a test similar to test_encode_datetime but using a datetime with microseconds like datetime(2025, 1, 1, 0, 0, 0, 123456, timezone.utc).
Summary
Fixes #1126 by using the native
timestamppackage function to convert the datetime directly to a float number, avoiding the lose of microseconds precision.A very similar change was merged at #821.
Converting directly to float should be no problem since you can already bypass this limitation by converting the datetimes to float yourselt. Code
produces