Jaydog
Jaydog

Reputation: 622

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)?

Upvotes: 1

Views: 8523

Answers (5)

Shiva
Shiva

Reputation: 2838

We can also use time and then format using the strftime method.

import datetime

dt = datetime.time(0, 10, 0)

dt.strftime('%H:%M:%S')

Upvotes: 2

tech2097
tech2097

Reputation: 36

for less than 24 hours work well

print(str(datetime.timedelta(minutes=10)).zfill(8))

"00:10:00"

when you exceed 24 hours, it looks like

print(str(datetime.timedelta(minutes=1445)).zfill(8))

"1 day, 0:05:00"

Upvotes: 1

glglgl
glglgl

Reputation: 91017

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.

Upvotes: 1

Jaydog
Jaydog

Reputation: 622

"{:0>8}".format(str(td))
# result: "00:10:00"

Upvotes: 5

rrrttt
rrrttt

Reputation: 469

td = datetime.timedelta(minutes=10)
time = '0'+str(td)
print(time)

The output is

00:10:00

Upvotes: 0

Related Questions