Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow passing timestamp to constructor of uuid7 #174

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/uuid6/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def uuid6(node: Optional[int] = None, clock_seq: Optional[int] = None) -> UUID:
return UUID(int=uuid_int, version=6)


def uuid7() -> UUID:
def uuid7(at_ts_ms = None) -> UUID:
r"""UUID version 7 features a time-ordered value field derived from the
widely implemented and well known Unix Epoch timestamp source, the
number of milliseconds since midnight 1 Jan 1970 UTC, leap seconds
Expand All @@ -137,11 +137,14 @@ def uuid7() -> UUID:

global _last_v7_timestamp

nanoseconds = time.time_ns()
timestamp_ms = nanoseconds // 10**6
if _last_v7_timestamp is not None and timestamp_ms <= _last_v7_timestamp:
timestamp_ms = _last_v7_timestamp + 1
_last_v7_timestamp = timestamp_ms
if at_ts_ms is None:
nanoseconds = time.time_ns()
timestamp_ms = nanoseconds // 10**6
if _last_v7_timestamp is not None and timestamp_ms <= _last_v7_timestamp:
timestamp_ms = _last_v7_timestamp + 1
_last_v7_timestamp = timestamp_ms
else:
timestamp_ms = at_ts_ms
uuid_int = (timestamp_ms & 0xFFFFFFFFFFFF) << 80
uuid_int |= secrets.randbits(76)
return UUID(int=uuid_int, version=7)
Expand Down