# level 4:Human readable duration format(2019-12-07)
###### tags: `Codewars` `python`
Your task in order to complete this Kata is to write a function which formats a duration, given as a number of seconds, in a human-friendly way.
The function must accept a non-negative integer. If it is zero, it just returns "now". Otherwise, the duration is expressed as a combination of years, days, hours, minutes and seconds.
It is much easier to understand with an example:
<pre>
format_duration(62) # returns "1 minute and 2 seconds"
format_duration(3662) # returns "1 hour, 1 minute and 2 seconds"
</pre>
For the purpose of this Kata, a year is 365 days and a day is 24 hours.
Note that spaces are important.
Detailed rules
The resulting expression is made of components like 4 seconds, 1 year, etc. In general, a positive integer and one of the valid units of time, separated by a space. The unit of time is used in plural if the integer is greater than 1.
The components are separated by a comma and a space (", "). Except the last component, which is separated by " and ", just like it would be written in English.
A more significant units of time will occur before than a least significant one. Therefore, 1 second and 1 year is not correct, but 1 year and 1 second is.
Different components have different unit of times. So there is not repeated units like in 5 seconds and 1 second.
A component will not appear at all if its value happens to be zero. Hence, 1 minute and 0 seconds is not valid, but it should be just 1 minute.
A unit of time must be used "as much as possible". It means that the function should not return 61 seconds, but 1 minute and 1 second instead. Formally, the duration specified by of a component must not be greater than any valid more significant unit of time.
my code:
<pre>
def count(item, time):
count=0
for i in time[(item + 1):]:
if i != 0:
count = count+1
return count
def format_duration(sec):
time = [0, 0, 0, 0, 0]
time[4] = sec % 60
time[3] = int(sec / 60) % 60
time[2] = int(int(sec / 60) / 60) % 24
time[1] = int(int(int(sec / 60) / 60) / 24)%365
time[0] = int(int(int(int(sec /60) / 60) /24) /365)
ans = ''
for i in range(0,len(time)):
m = ''
if time[i] > 0:
m = str(time[i])
if i == 0:
m = m + ' year' if time[i] == 1 else m + ' years'
if i == 1:
m = m + ' day' if time[i] == 1 else m + ' days'
if i == 2:
m = m + ' hour' if time[i] == 1 else m + ' hours'
if i == 3:
m = m + ' minute' if time[i] == 1 else m + ' minutes'
if i == 4:
m = m + ' second' if time[i] == 1 else m + ' seconds'
if i != 4 and time[i]>0:
c = count(i, time)
if c > 0:
m = m + ' and 'if c==1 else m + ', '
ans = ans + m
if sec == 0:
return 'now'
else:
return ans