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

Add UUID timestamp property #22

Merged
merged 2 commits into from
Aug 11, 2023
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions python/uuid_utils/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ class UUID:
@property
def time_mid(self) -> _Int: ...
@property
def timestamp(self) -> _Int:
"""Get UUID timestamp milliseconds since epoch.
Only works for UUID versions 1, 6 and 7, otherwise raises ValueError."""
...
@property
def urn(self) -> str: ...
@property
def variant(self) -> str: ...
Expand Down
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,21 @@ impl UUID {
high.wrapping_shl(48) | mid.wrapping_shl(32) | self.time_low() as u64
}

#[getter]
fn timestamp(&self) -> PyResult<u64> {
match self.uuid.get_timestamp() {
Some(timestamp) => {
let (secs, nanos) = timestamp.to_unix();
Ok(secs * 1_000 + nanos as u64 / 1_000 / 1_000)
}
_ => {
return Err(PyErr::new::<PyValueError, &str>(
"UUID version should be one of (v1, v6 or v7).",
))
}
}
}

#[getter]
fn fields(&self) -> PyResult<(u32, u16, u16, u8, u8, u64)> {
Ok((
Expand Down
8 changes: 8 additions & 0 deletions tests/test_uuid.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,11 @@ def test_uuid_properties() -> None:
assert uuid_1.urn == uuid_2.urn
assert uuid_1.variant == uuid_2.variant
assert uuid_1.version == uuid_2.version


def test_uuid_timestamp() -> None:
uuid = uuid_utils.uuid7(1679665408)
assert uuid.timestamp == 1679665408000

with pytest.raises(ValueError):
uuid_utils.uuid4().timestamp