How to format duration in Python (timedelta)?

32.1k views Asked by At

I'm a newbie to python. I was trying to display the time duration. What I did was:

startTime = datetime.datetime.now().replace(microsecond=0)
... <some more codes> ...
endTime = datetime.datetime.now().replace(microsecond=0)
durationTime = endTime - startTime
print("The duration is " + str(durationTime))

The output is => The duration is 0:01:28 Can I know how to remove hour from the result? I want to display => The duration is 01:28

Thanks in advance!

2

There are 2 answers

2
ssundarraj On BEST ANSWER

You can do this by converting durationTime which is a datetime.timedelta object to a datetime.time object and then using strftime.

print datetime.time(0, 0, durationTime.seconds).strftime("%M:%S")

Another way would be to manipulate the string:

print ':'.join(str(durationTime).split(':')[1:])
1
Zack Tanner On

You can split your timedelta as follows:

>>> hours, remainder = divmod(durationTime.total_seconds(), 3600)
>>> minutes, seconds = divmod(remainder, 60)
>>> print '%s:%s' % (minutes, seconds)

This will use python's builtin divmod to convert the number of seconds in your timedelta to hours, and the remainder will then be used to calculate the minutes and seconds. You can then explicitly print the units of time you want.