Last active
September 15, 2023 13:48
-
-
Save CHERTS/60a3c8ba1125eb38e9df96cd4a0b710b to your computer and use it in GitHub Desktop.
Native UUIDv7 on Python 3
This file contains 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 | |
import uuid | |
import datetime | |
# UUID v7 format: | |
# 0 1 2 3 | |
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
# | unixts | | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
# |unixts | subsec_a | ver | subsec_b | | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
# |var| subsec_seq_node | | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
# | subsec_seq_node | | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
def uuid7_native(unix_ts_ms: int = None): | |
if unix_ts_ms is None: | |
unix_ts_ms = time.time_ns() // 1000000 | |
ver = 7 | |
variant = 2 | |
rand_a = 0 | |
rand_b = 0 | |
#rand_a = random.getrandbits(12) | |
#rand_b = random.getrandbits(62) | |
# Offsets: | |
# | |
# unix_ts_ms = 128 - 48 = 80 | |
# ver = 80 - 4 = 76 | |
# rand_a = 76 - 12 = 64 | |
# variant = 64 - 2 = 62 | |
# rand_b = 62 - 62 = 0 | |
return uuid.UUID(int=(unix_ts_ms << 80) + (ver << 76) + (rand_a << 64) + (variant << 62) + rand_b) | |
dt = datetime.datetime.strptime("2023-06-01 00:00:00", "%Y-%m-%d %H:%M:%S").replace(tzinfo=datetime.timezone.utc) | |
timestamp_ms = int(dt.timestamp() * 1000) | |
boundary_uuid = uuid7_native(timestamp_ms) | |
print("Date: %s\n" % (dt)) | |
print("UUID: %s\n" % boundary_uuid) | |
boundary_uuid = uuid7_native() | |
print("Now date/time UUID: %s\n" % boundary_uuid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment