Home > Backend Development > Python Tutorial > How Can I Display a Python timedelta Object as Hours:Minutes?

How Can I Display a Python timedelta Object as Hours:Minutes?

Susan Sarandon
Release: 2025-01-04 21:32:40
Original
245 people have browsed it

How Can I Display a Python timedelta Object as Hours:Minutes?

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
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template