Skip to content

Instantly share code, notes, and snippets.

@mgd020
Last active February 11, 2025 22:41
Show Gist options
  • Save mgd020/d6a0ff28d7b3658133e97fe1063c0a0c to your computer and use it in GitHub Desktop.
Save mgd020/d6a0ff28d7b3658133e97fe1063c0a0c to your computer and use it in GitHub Desktop.
UUID7 functions for Python
import random
import time
from uuid import UUID
UUID7_MASK = ((1 << 80) - 1) ^ (0xf << 76) ^ (0x3 << 62)
UUID7_SET = (0x7 << 76) | (0x2 << 62)
def uuid7() -> UUID:
unix_ts_ms = ((time.time_ns() // 1_000_000) << 80) | UUID7_SET
rand = random.getrandbits(80) & UUID7_MASK
return UUID(int=unix_ts_ms | rand)
def uuid7_batch(n: int) -> list[UUID]:
mask = UUID7_MASK
getrandbits = random.getrandbits
unix_ts_ms = ((time.time_ns() // 1_000_000) << 80) | UUID7_SET
return [UUID(int=unix_ts_ms | (getrandbits(80) & mask)) for _ in range(n)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment