Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format duration in Python (timedelta)? [duplicate]

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!

like image 751
Yin Avatar asked Mar 17 '26 02:03

Yin


1 Answers

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.

like image 123
Zack Tanner Avatar answered Mar 18 '26 15:03

Zack Tanner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!