Home >Backend Development >Python Tutorial >How to Easily Format a `datetime.timedelta` Object to Hours:Minutes?
Format timedelta to String
Confronting the hurdle of formatting a datetime.timedelta object, particularly to display the duration in the customary hours:minutes format, is a common challenge.
To address this, one commonly attempted approach involves adding methods to the object's class that separately extract the hours and minutes. While obtaining the hours can be achieved by dividing the timedelta.seconds by 3600, the conversion of the remaining seconds to minutes poses a difficulty.
A simplified approach exists that effectively circumvents these complexities. Employing the str() function on the timedelta object directly yields the desired string representation. As exemplified below:
import datetime start = datetime.datetime(2009, 2, 10, 14, 00) end = datetime.datetime(2009, 2, 10, 16, 00) delta = end - start print(str(delta)) # prints 2:00:00
The above is the detailed content of How to Easily Format a `datetime.timedelta` Object to Hours:Minutes?. For more information, please follow other related articles on the PHP Chinese website!