Created
March 5, 2026 13:29
-
-
Save idcesares/a38c76f6bf2fc423604b9126f785728a to your computer and use it in GitHub Desktop.
Minimal Python UUIDv7 Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import time | |
| import secrets | |
| import uuid | |
| def uuid7(): | |
| # 48-bit Unix timestamp in milliseconds | |
| ts = int(time.time() * 1000) & ((1 << 48) - 1) | |
| # 74 bits of randomness | |
| rand = secrets.randbits(74) | |
| # Construct UUID integer | |
| value = (ts << 80) | rand | |
| # Set version (7) | |
| value &= ~(0xF << 76) | |
| value |= (0x7 << 76) | |
| # Set variant (10xx) | |
| value &= ~(0x3 << 62) | |
| value |= (0x2 << 62) | |
| return uuid.UUID(int=value) | |
| print(uuid7()) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How It Works (Step-by-Step)
1️⃣ Timestamp
This gives:
Stored in the first 48 bits.
That’s why UUIDv7 values are chronologically sortable.
2️⃣ Randomness
This fills the remaining bits to ensure global uniqueness.
The
secretsmodule is used instead ofrandombecause it’s cryptographically secure.3️⃣ Bit Layout
We assemble the UUID as a 128-bit integer.
This shifts the timestamp into the top bits.
Then randomness fills the rest.
4️⃣ Version Bits
Binary:
This marks the UUID as version 7.
5️⃣ Variant Bits
Binary:
This is the RFC 4122 variant used by almost all UUIDs.