Last active
February 11, 2025 22:41
-
-
Save mgd020/d6a0ff28d7b3658133e97fe1063c0a0c to your computer and use it in GitHub Desktop.
UUID7 functions for Python
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 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