-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-human_duration.py
37 lines (29 loc) · 939 Bytes
/
4-human_duration.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
def format_duration(seconds):
if seconds == 0:
return 'now'
dur_parts = [
('year', seconds // (86400 * 365)),
('day', (seconds // 86400) % 365),
('hour', (seconds // 3600) % 24),
('minute', (seconds // 60) % 60),
('second', seconds % 60)
]
non_zero = 0
for e in dur_parts:
if e[1] > 0:
non_zero += 1
retval = ''
for e in dur_parts:
if e[1] > 0:
retval += '{:d} {}{}'.format(e[1], e[0], 's' if e[1] > 1 else '')
if non_zero > 2:
retval += ', '
elif non_zero == 2:
retval += ' and '
non_zero -= 1
return retval
print(format_duration(1), "1 second")
print(format_duration(62), "1 minute and 2 seconds")
print(format_duration(120), "2 minutes")
print(format_duration(3600), "1 hour")
print(format_duration(3662), "1 hour, 1 minute and 2 seconds")