Repository navigation
Expand file tree
/
Copy pathtime.py
More file actions
147 lines (123 loc) · 4.35 KB
/
Copy pathtime.py
File metadata and controls
147 lines (123 loc) · 4.35 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import six
import time
import typing
import datetime
import itertools
delta_type = typing.Union[datetime.timedelta, int, float]
# There might be a better way to get the epoch with tzinfo, please create
# a pull request if you know a better way that functions for Python 2 and 3
epoch = datetime.datetime(year=1970, month=1, day=1)
def timedelta_to_seconds(delta):
'''Convert a timedelta to seconds with the microseconds as fraction
Note that this method has become largely obsolete with the
`timedelta.total_seconds()` method introduced in Python 2.7.
>>> from datetime import timedelta
>>> '%d' % timedelta_to_seconds(timedelta(days=1))
'86400'
>>> '%d' % timedelta_to_seconds(timedelta(seconds=1))
'1'
>>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1))
'1.000001'
>>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1))
'0.000001'
'''
# Only convert to float if needed
if delta.microseconds:
total = delta.microseconds * 1e-6
else:
total = 0
total += delta.seconds
total += delta.days * 60 * 60 * 24
return total
def format_time(timestamp, precision=datetime.timedelta(seconds=1)):
'''Formats timedelta/datetime/seconds
>>> format_time('1')
'0:00:01'
>>> format_time(1.234)
'0:00:01'
>>> format_time(1)
'0:00:01'
>>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> format_time(datetime.date(2000, 1, 2))
'2000-01-02'
>>> format_time(datetime.timedelta(seconds=3661))
'1:01:01'
>>> format_time(None)
'--:--:--'
>>> format_time(format_time) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Unknown type ...
'''
precision_seconds = precision.total_seconds()
if isinstance(timestamp, six.string_types + six.integer_types + (float, )):
try:
castfunc = six.integer_types[-1]
timestamp = datetime.timedelta(seconds=castfunc(timestamp))
except OverflowError: # pragma: no cover
timestamp = None
if isinstance(timestamp, datetime.timedelta):
seconds = timestamp.total_seconds()
# Truncate the number to the given precision
seconds = seconds - (seconds % precision_seconds)
return str(datetime.timedelta(seconds=seconds))
elif isinstance(timestamp, datetime.datetime): # pragma: no cover
# Python 2 doesn't have the timestamp method
if hasattr(timestamp, 'timestamp'):
seconds = timestamp.timestamp()
else:
seconds = timedelta_to_seconds(timestamp - epoch)
# Truncate the number to the given precision
seconds = seconds - (seconds % precision_seconds)
try: # pragma: no cover
if six.PY3:
dt = datetime.datetime.fromtimestamp(seconds)
else:
dt = datetime.datetime.utcfromtimestamp(seconds)
except ValueError: # pragma: no cover
dt = datetime.datetime.max
return str(dt)
elif isinstance(timestamp, datetime.date):
return str(timestamp)
elif timestamp is None:
return '--:--:--'
else:
raise TypeError('Unknown type %s: %r' % (type(timestamp), timestamp))
def timeout_generator(
timeout: delta_type,
interval: delta_type = datetime.timedelta(seconds=1),
iterable=itertools.count,
):
'''
Generator that walks through the given iterable (a counter by default)
until the timeout is reached with a configurable interval between items
>>> for i in timeout_generator(0.1, 0.06):
... print(i)
0
1
2
>>> timeout = datetime.timedelta(seconds=0.1)
>>> interval = datetime.timedelta(seconds=0.06)
>>> for i in timeout_generator(timeout, interval, itertools.count()):
... print(i)
0
1
2
>>> for i in timeout_generator(1, interval=0.1, iterable='ab'):
... print(i)
a
b
'''
if isinstance(interval, datetime.timedelta):
interval = timedelta_to_seconds(interval)
if isinstance(timeout, datetime.timedelta):
timeout = timedelta_to_seconds(timeout)
if callable(iterable):
iterable = iterable()
end = timeout + time.perf_counter()
for item in iterable:
yield item
if time.perf_counter() >= end:
break
time.sleep(interval)