uuid.py 891 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. """Public UUID v7 helpers.
  2. These helpers expose utilities for generating UUID v7 identifiers in user code.
  3. """
  4. from __future__ import annotations
  5. import datetime as _dt
  6. import uuid as _uuid
  7. from ._internal._uuid import uuid7 as _uuid7
  8. def uuid7() -> _uuid.UUID:
  9. """Generate a random UUID v7.
  10. Returns:
  11. uuid.UUID: A random, RFC 9562-compliant UUID v7.
  12. """
  13. return _uuid7()
  14. def uuid7_from_datetime(dt: _dt.datetime) -> _uuid.UUID:
  15. """Generate a UUID v7 from a datetime.
  16. Args:
  17. dt: A timezone-aware datetime. If naive, it is treated as UTC.
  18. Returns:
  19. uuid.UUID: A UUID v7 whose timestamp corresponds to the provided time.
  20. """
  21. if dt.tzinfo is None:
  22. dt = dt.replace(tzinfo=_dt.timezone.utc)
  23. nanoseconds = int(dt.timestamp() * 1_000_000_000)
  24. return _uuid7(nanoseconds)
  25. __all__ = ["uuid7", "uuid7_from_datetime"]