49 lines
1.3 KiB
Markdown
49 lines
1.3 KiB
Markdown
# UUIDv7 for Python
|
|
|
|
A simple module for generating UUIDv7 that contain creation
|
|
timestamps. Another function for extracting the time of an UUID.
|
|
|
|
- **Standard compliant**: Follows the final UUIDv7 specification (drafts were different)
|
|
- **Pythonic**: Uses stdlib `datetime` and `UUID` facilities rather than bare strings and milliseconds.
|
|
|
|
Note: As of writing, Python itself has no UUIDv7 support yet.
|
|
|
|
## Installation
|
|
|
|
```sh
|
|
pip install uuid7
|
|
```
|
|
|
|
Or for your project using [uv](https://docs.astral.sh/uv/):
|
|
```sh
|
|
uv add uuid7
|
|
```
|
|
|
|
## Usage
|
|
|
|
```python
|
|
import uuid7
|
|
from datetime import datetime, UTC
|
|
from uuid import UUID
|
|
|
|
# Create a random UUIDv7 with current timestamp
|
|
u = uuid7.create()
|
|
|
|
# Create a UUIDv7 with specific timestamp
|
|
when = datetime(1970, 1, 1, tzinfo=UTC)
|
|
u = uuid7.create(when)
|
|
|
|
# Extract timestamp
|
|
u = UUID('00000000-0000-7dac-b3e3-ecb571bb3e2f')
|
|
timestamp = uuid7.time(u) # 1970-01-01 UTC
|
|
```
|
|
|
|
### `create(when: datetime?) -> UUID`
|
|
|
|
Create a UUIDv7 with timestamp-based ordering. If a datetime object is passed,uses that (local time or timezone-aware) timestamp rather than current time. This is useful e.g. for creating a bunch of UUIDv7 is precisely same timestamp.
|
|
|
|
### `extract_time(u: UUID) -> datetime`
|
|
|
|
Extract the timestamp from a UUIDv7. Raises ValueError if the UUID is not a UUIDv7.
|
|
|
|
### `UUID() |