1
1
from datetime import timedelta , datetime , timezone
2
+ from enum import StrEnum
2
3
3
4
4
- def _to_datetime (v ):
5
+ class Resolution (StrEnum ):
6
+ Seconds = "s"
7
+ MilliSeconds = "ms"
8
+ MicroSeconds = "us"
9
+ NanoSeconds = "ns"
10
+
11
+
12
+ def _to_datetime (v , resolution = Resolution .Seconds ):
5
13
if isinstance (v , datetime ):
6
14
return v
7
15
elif isinstance (v , (int , float )):
8
- return datetime .fromtimestamp (v , timezone .utc )
16
+ resolution = Resolution (resolution )
17
+ to_secs_d = {
18
+ Resolution .Seconds : 1 ,
19
+ Resolution .MilliSeconds : 1_000 ,
20
+ Resolution .MicroSeconds : 1_000_000 ,
21
+ Resolution .NanoSeconds : 1_000_000_000 ,
22
+ }[resolution ]
23
+ return datetime .fromtimestamp (v / to_secs_d , timezone .utc )
9
24
elif isinstance (v , str ):
10
25
return datetime .fromisoformat (v )
11
26
else :
12
27
assert False , f"cannot convert { v } to datetime"
13
28
14
29
15
30
class _WithinBounds :
16
- def __init__ (self , lower_bound , upper_bound ):
31
+ def __init__ (self , lower_bound , upper_bound , expect_resolution = Resolution . Seconds ):
17
32
self ._lower_bound = lower_bound
18
33
self ._upper_bound = upper_bound
34
+ self ._expect_resolution = expect_resolution
19
35
20
36
def __eq__ (self , other ):
21
- other = _to_datetime (other )
37
+ other = _to_datetime (other , resolution = self . _expect_resolution )
22
38
return self ._lower_bound <= other <= self ._upper_bound
23
39
24
40
def __str__ (self ):
@@ -28,18 +44,18 @@ def __repr__(self) -> str:
28
44
return str (self )
29
45
30
46
31
- def time_after (lower_bound ):
47
+ def time_after (lower_bound , ** kwargs ):
32
48
upper_bound = datetime .now (tz = timezone .utc )
33
- return time_within (lower_bound , upper_bound )
49
+ return time_within (lower_bound , upper_bound , ** kwargs )
34
50
35
51
36
- def time_within (lower_bound , upper_bound ):
52
+ def time_within (lower_bound , upper_bound , ** kwargs ):
37
53
lower_bound = _to_datetime (lower_bound )
38
54
upper_bound = _to_datetime (upper_bound )
39
55
assert lower_bound <= upper_bound
40
- return _WithinBounds (lower_bound , upper_bound )
56
+ return _WithinBounds (lower_bound , upper_bound , ** kwargs )
41
57
42
58
43
- def time_within_delta (time = None , delta = timedelta (seconds = 30 )):
59
+ def time_within_delta (time = None , delta = timedelta (seconds = 30 ), ** kwargs ):
44
60
time = _to_datetime (time ) if time is not None else datetime .now (tz = timezone .utc )
45
- return _WithinBounds (time - delta , time + delta )
61
+ return _WithinBounds (time - delta , time + delta , ** kwargs )
0 commit comments