Skip to content

Instantly share code, notes, and snippets.

@idcesares
Created March 5, 2026 13:29
Show Gist options
  • Select an option

  • Save idcesares/a38c76f6bf2fc423604b9126f785728a to your computer and use it in GitHub Desktop.

Select an option

Save idcesares/a38c76f6bf2fc423604b9126f785728a to your computer and use it in GitHub Desktop.
Minimal Python UUIDv7 Implementation
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())
@idcesares
Copy link
Author

How It Works (Step-by-Step)

1️⃣ Timestamp

ts = int(time.time() * 1000)

This gives:

milliseconds since Unix epoch

Stored in the first 48 bits.

That’s why UUIDv7 values are chronologically sortable.


2️⃣ Randomness

secrets.randbits(74)

This fills the remaining bits to ensure global uniqueness.

The secrets module is used instead of random because it’s cryptographically secure.


3️⃣ Bit Layout

We assemble the UUID as a 128-bit integer.

timestamp << 80

This shifts the timestamp into the top bits.

Then randomness fills the rest.


4️⃣ Version Bits

value |= (0x7 << 76)

Binary:

0111

This marks the UUID as version 7.


5️⃣ Variant Bits

value |= (0x2 << 62)

Binary:

10xx

This is the RFC 4122 variant used by almost all UUIDs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment