-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeUUID.py
100 lines (76 loc) · 2.87 KB
/
timeUUID.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import time
import datetime
class TimeUUID():
def __init__(self, hex=None, timestamp=None, timedelta=None):
if hex is not None:
if timestamp is not None:
raise TypeError('Can not change timestamp of TimeUUID when initializing from hex value.')
hex = hex.replace('-', '')
if len(hex) != 32:
raise ValueError('Improperly formed TimeUUID hex string')
self.__dict__['int'] = int(hex, 16)
self.__dict__['timestamp'] = (self.int >> 64) * 100 / 1e9
return
if timestamp is not None:
if timestamp < 0:
raise ValueError('Timestamp out of range')
elif isinstance(timedelta, datetime.timedelta):
timestamp = (datetime.datetime.now() - timedelta).timestamp()
else:
timestamp = time.time()
nanoseconds = int(timestamp * 1e9)
time_bytes = int(nanoseconds/100)
try:
import os
random_bytes = os.urandom(8)
except:
import random
random_bytes = bytes(random.randrange(256) for i in range(8))
random_bytes = int.from_bytes(random_bytes, byteorder="big")
self.__dict__['int'] = ((time_bytes << 64) | random_bytes)
self.__dict__['timestamp'] = time_bytes * 100 / 1e9
def __eq__(self, other):
if isinstance(other, TimeUUID):
return self.int == other.int
return NotImplemented
def __ne__(self, other):
if isinstance(other, TimeUUID):
return self.int != other.int
return NotImplemented
def __gt__(self, other):
if isinstance(other, TimeUUID):
return self.int > other.int
return NotImplemented
def __lt__(self, other):
if isinstance(other, TimeUUID):
return self.int < other.int
return NotImplemented
def __ge__(self, other):
if isinstance(other, TimeUUID):
return self.int >= other.int
return NotImplemented
def __le__(self, other):
if isinstance(other, TimeUUID):
return self.int <= other.int
return NotImplemented
def __int__(self):
return self.int
def __repr__(self):
return 'TimeUUID(%r)' % str(self)
def __setattr__(self, name, value):
raise TypeError('TimeUUID objects are immutable')
def __str__(self):
hex = '%032x' % self.int
return '%s-%s-%s-%s-%s' % (
hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])
def __hash__(self):
return hash(self.int)
@property
def time(self):
return self.timestamp
@property
def datetime(self):
return datetime.datetime.fromtimestamp(self.timestamp)
@property
def hex(self):
return '%032x' % self.int