Home >Backend Development >Python Tutorial >How Can Python\'s `datetime.timedelta` Convert Seconds to Hours, Minutes, and Seconds?

How Can Python\'s `datetime.timedelta` Convert Seconds to Hours, Minutes, and Seconds?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 12:24:13613browse

How Can Python's `datetime.timedelta` Convert Seconds to Hours, Minutes, and Seconds?

Converting Seconds to Hours, Minutes, and Seconds in Python

While working with time-related data, it's often necessary to convert seconds into a more readable format, typically hours, minutes, and seconds. This article will demonstrate how to efficiently achieve this conversion in Python.

Solution Using datetime.timedelta

Python's datetime module provides a convenient function called datetime.timedelta that facilitates the conversion of seconds to the desired format:

import datetime
seconds = 666
time_string = str(datetime.timedelta(seconds=seconds))
print(time_string)

Output:

0:11:06

This line of code takes the number of seconds (666 in this example) and creates a timedelta object with that value. The str() function is then called on the timedelta object to convert it into a string representation in the format 'hours:minutes:seconds':

The above is the detailed content of How Can Python\'s `datetime.timedelta` Convert Seconds to Hours, Minutes, and Seconds?. 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