Home > Backend Development > Python Tutorial > How to Easily Format a `datetime.timedelta` Object to Hours:Minutes?

How to Easily Format a `datetime.timedelta` Object to Hours:Minutes?

Linda Hamilton
Release: 2024-12-15 04:44:13
Original
891 people have browsed it

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

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!

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