简体   繁体   中英

How to convert this duration into days/hours/minutes/seconds in Python/Django?

I have a duration like this:

(1, 2, 3, 11)

It's in days/hours/minutes/seconds format. How can I show something like: 1 days, 2 hours and 3 minutes . I don't need seconds. So, if the duration is:

(0, 2, 3, 1)

It should be shown like 2 hours and 3 minutes . If the duration is:

(0, 0, 3, 11)

It should be shown like 3 minutes.

How can I achieve that? Thanks

This is an edited answer for Python 2.6 and English singular/plural:

def f(x):
    parts = ['%d %s%s' % (a, p, ('', 's')[a > 1]) for a,p in zip(x, ('day', 'hour', 'minute')) if a]
    return ' and '.join(c for c in [', '.join(parts[:-1]), parts[-1]] if c)

Test:

>>> print f((1, 2, 3, 11))
1 day, 2 hours and 3 minutes

>>> print f((0, 2, 3, 1))
2 hours and 3 minutes

>>> print f((0, 0, 3, 11))
3 minutes

How much are you going to be doing this?

If it's a lot, and will be repeated a lot, you could just write a function to do it for you;

def days(t):
    oxford_comma = False
    a = [" day", " hour", " minute"]
    s = []
    if len(t) != 4:
        return "incorrect format"
    else:
        for i in range(3):
            if t[i] != 0:
                plural = "s" if t[i] > 1 else ""
                s.append(str(t[i]) + a[i] + plural + ", ")


        if len(s) > 1:
            if not oxford_comma:
                s[-2] = s[-2].replace(",","")
            s.insert(len(s)-1,"and ")
        return "".join(s)[:-2]


    print days((1,2,3,11))      #1 day, 2 hours, and 3 minutes
    print days((0,2,3,1))       #2 hours, and 3 minutes
    print days((0,0,3,11))      #3 minutes
    print days((1,1,1,11))      #1 day, 1 hour, and 1 minute

Change oxford_comma if you want it.

It also takes into account plurals.

Sorry it's a bit messy - it could definitely be cleaned up - was rushed!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM