Home >Backend Development >Python Tutorial >How Can I Convert a datetime.timedelta Object to an Hours:Minutes String?

How Can I Convert a datetime.timedelta Object to an Hours:Minutes String?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 06:56:18617browse

How Can I Convert a datetime.timedelta Object to an Hours:Minutes String?

Converting a datetime.timedelta Object to a String in Hours:Minutes Format

Problem:

Formatting a datetime.timedelta object to display the duration in hours and minutes can be challenging. Converting the remaining seconds to minutes poses particular difficulties.

Solution:

Rather than implementing custom methods, a simpler solution lies in using the str() function to convert the timedelta object directly into a string. Here's an example:

import datetime

start = datetime.datetime(2009, 2, 10, 14, 00)
end = datetime.datetime(2009, 2, 10, 16, 00)
delta = end - start

print(str(delta))

This will output the string "2:00:00", where 2 represents the hours and 00 represents the minutes.

The above is the detailed content of How Can I Convert a datetime.timedelta Object to an Hours:Minutes String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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