Home >Backend Development >Python Tutorial >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!