Skip to content

Commit 9a92a2c

Browse files
authored
Add time property (#6)
1 parent 37d420f commit 9a92a2c

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

src/uuid6/__init__.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
class DraftUUID(UUID):
1111
r"""UUID draft version objects"""
1212

13-
def __init__(self, int: int, version: int = None):
13+
def __init__(self, int: int, version: int = None) -> None:
1414
r"""Create a UUID from a single 128-bit integer as the 'int' argument."""
1515

1616
if not 0 <= int < 1 << 128:
@@ -26,6 +26,30 @@ def __init__(self, int: int, version: int = None):
2626
int |= version << 76
2727
super().__init__(int=int)
2828

29+
@property
30+
def subsec(self) -> int:
31+
return (
32+
(self.time_mid & 0x0FFF) << 18
33+
| (self.time_hi_version & 0x0FFF) << 6
34+
| self.clock_seq_hi_variant & 0x3F
35+
)
36+
37+
@property
38+
def time(self) -> int:
39+
if self.version == 6:
40+
return (
41+
(self.time_low << 28)
42+
| (self.time_mid << 12)
43+
| (self.time_hi_version & 0x0FFF)
44+
)
45+
if self.version == 7:
46+
return self.unixts * 10 ** 9 + self.subsec
47+
return super().time
48+
49+
@property
50+
def unixts(self) -> int:
51+
return self.time_low << 4 | self.time_mid >> 12
52+
2953

3054
def _getrandbits(k: int) -> int:
3155
import random

test/test_uuid6.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import unittest
2+
from time import time_ns
23
from unittest.mock import patch
4+
from uuid import uuid1
35

46
from uuid6 import DraftUUID, uuid6, uuid7
57

6-
78
YEAR_IN_NS = 3600 * 24 * 36525 * 10 ** 7
89

910

@@ -33,6 +34,7 @@ def test_invalid_int(self):
3334
def test_valid_int(self):
3435
test_uuid = DraftUUID(int=0)
3536
self.assertEqual(test_uuid.version, None)
37+
self.assertEqual(test_uuid.time, 0)
3638
test_uuid = DraftUUID(int=(1 << 128) - 1)
3739
self.assertEqual(test_uuid.version, None)
3840

@@ -96,6 +98,14 @@ def test_uuid7_far_in_future(self):
9698
uuid_2178_from_epoch = uuid7()
9799
self.assertLess(uuid_2178_from_epoch, uuid_prev)
98100

101+
def test_time(self):
102+
uuid_1 = uuid1()
103+
uuid_6 = uuid6()
104+
self.assertAlmostEqual(uuid_6.time / 10 ** 7, uuid_1.time / 10 ** 7, 3)
105+
cur_time = time_ns()
106+
uuid_7 = uuid7()
107+
self.assertAlmostEqual(uuid_7.time / 10 ** 9, cur_time / 10 ** 9, 3)
108+
99109

100110
if __name__ == "__main__":
101111
unittest.main()

0 commit comments

Comments
 (0)