Search code examples
pythonstringdatetimedatetime-formattimedelta

How to convert a python timedelta to a string that has a leading zero so it retains the format "00:00:00" (%HH:%MM:%SS)


Given a timedelta in python such as:

td = datetime.timedelta(minutes=10)

if printed as a string it appears without the leading zero I want:

t_str = string(td)
print(t_str)
# result: "0:10:00"

How can I convert it to a string that retains the format of "00:10:00" (%HH:%MM:%SS)?


Solution

  • It is a bit tricky, because the behaviour for negative values as well as values longer than a day is more complicated.

    def str_td(td):
        s = str(td).split(", ", 1)
        a = s[-1]
        if a[1] == ':':
            a = "0" + a
        s2 = s[:-1] + [a]
        return ", ".join(s2)
    
    print(str_td(datetime.timedelta(minutes=10)))
    print(str_td(datetime.timedelta(minutes=3200)))
    print(str_td(datetime.timedelta(minutes=-1400)))
    print(str_td(datetime.timedelta(seconds=4003.2)))
    print(str_td(datetime.timedelta(seconds=86401.1)))
    

    gives

    00:10:00
    2 days, 05:20:00
    -1 day, 00:40:00
    01:06:43.200000
    1 day, 00:00:01.100000
    

    A completely different way of doing it would be

    def str_td(td):
        s = str(td).split(", ", 1)
        t = datetime.time(td.seconds // 3600,td.seconds // 60 % 60,td.seconds % 60, td.microseconds)
        s2 = s[:-1] + [str(t)]
        return ", ".join(s2)
    
    print(str_td(datetime.timedelta(minutes=10)))
    print(str_td(datetime.timedelta(minutes=3200)))
    print(str_td(datetime.timedelta(minutes=-1400)))
    print(str_td(datetime.timedelta(seconds=4003.2)))
    print(str_td(datetime.timedelta(seconds=86401.1)))
    

    which gives the same result as above.

    Which one is more elegant is left as an exercise to the reader.