Format duration in minutes as weeks, days, hours, minutes

507 views Asked by At

I've got a list of elapsed times in minutes and I'm trying to reformat them as strings of weeks, days, hours and minutes.

So, for example, 7,480 minutes = 3 weeks, 4 hours and 40 minutes.

I'd like the format to be like so: '3w4h40m'

Using divmod I've written a function to break the minutes down into weeks, days, hours and minutes and return the string:

def formattime(time):
    tl = [divmod(divmod(divmod(time,60)[0],8)[0],5)[0],divmod(divmod(divmod(time,60)[0],8)[0],5)[1],divmod(divmod(time,60)[0],8)[1],divmod(time,60)[1]]

    timestring = str(tl[0])+'w'+str(tl[1])+'d'+str(tl[2])+'h'+str(tl[3])+'m'

    return timestring

However, I don't want it to return a figure for any of weeks, days, hours or minutes if the number is zero:

>>> formattime(7480)
'3w0d4h40m'

Is there a pythonic and straightforward way of returning '3w4h40m'?

1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

You could filter out the components at 0 if you had a list of them:

def formattime(time):
    # format to workweeks, workdays, hours and minutes
    # a workweek is 5 days, a workday is 8 hours
    hours, minutes = divmod(time, 60)
    days, hours = divmod(hours, 8)  # work days
    weeks, days = divmod(days, 5)   # work weeks
    components = [str(v) + l for l, v in zip('wdhm', (weeks, days, hours, minutes)) if v]
    return ''.join(components) or '0m'

Demo:

>>> formattime(7480)
'3w4h40m'
>>> formattime(0)
'0m'