Displaying timedelta as Hours:Minutes
Formatting a datetime.timedelta object to display hours and minutes can present challenges. Here's a solution to achieve this in Python:
Convert to String:
You can directly convert the timedelta to a string using str(). The resulting string will show the duration in the format 'hours:minutes:seconds'. For instance:
import datetime start = datetime.datetime(2009, 2, 10, 14, 00) end = datetime.datetime(2009, 2, 10, 16, 00) delta = end - start print(str(delta)) # Output: 2:00:00
Custom Class Methods:
If you prefer to create custom methods, you can add functions to your object's class for retrieving the hours and minutes. Calculate hours by dividing timedelta.seconds by 3600 and rounding it. To obtain the minutes, divide the remainder seconds by 60 and round the result.
class MyObject: def __init__(self, timedelta): self.timedelta = timedelta def get_hours(self): return round(self.timedelta.seconds / 3600) def get_minutes(self): return round((self.timedelta.seconds % 3600) / 60)
The above is the detailed content of How Can I Display a Python timedelta Object as Hours:Minutes?. For more information, please follow other related articles on the PHP Chinese website!