-
Notifications
You must be signed in to change notification settings - Fork 1
/
time.py
52 lines (44 loc) · 1.27 KB
/
time.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
import datetime
TIMESINCE_CHUNKS = (
(60 * 60 * 24 * 365, '%.1f\xa0years'),
(60 * 60 * 24 * 30, '%.1f\xa0months'),
(60 * 60 * 24 * 7, '%.1f\xa0weeks'),
(60 * 60 * 24, '%.1f\xa0days'),
(60 * 60, '%.1f\xa0hours'),
(60, '%.1f\xa0minutes'),
)
def human_timedelta(t):
"""
Converts a time duration into a friendly text representation.
>>> human_timedelta(0.001)
'1.0\xa0ms'
>>> human_timedelta(0.01)
'10.0\xa0ms'
>>> human_timedelta(0.9)
'900.0\xa0ms'
>>> human_timedelta(1)
'1.0\xa0seconds'
>>> human_timedelta(65.5)
'1.1\xa0minutes'
>>> human_timedelta(59 * 60)
'59.0\xa0minutes'
>>> human_timedelta(1.05*60*60)
'1.1\xa0hours'
>>> human_timedelta(24*60*60)
'1.0\xa0days'
>>> human_timedelta(2.54 * 60 * 60 * 24 * 365)
'2.5\xa0years'
"""
if isinstance(t, datetime.timedelta):
t = t.total_seconds()
assert isinstance(t, (int, float))
if abs(t) < 1:
return f'{round(t * 1000, 1):.1f}\xa0ms'
if abs(t) < 60:
return f'{round(t, 1):.1f}\xa0seconds'
for seconds, time_string in TIMESINCE_CHUNKS: # noqa: B007
count = t / seconds
if abs(count) >= 1:
count = round(count, 1)
break
return time_string % count