Home >Backend Development >Python Tutorial >How Can I Format a Python `timedelta` Object into a Human-Readable String?

How Can I Format a Python `timedelta` Object into a Human-Readable String?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 17:53:10324browse

How Can I Format a Python `timedelta` Object into a Human-Readable String?

Formatting timedelta to String

In Python, you can use the str() function to convert a datetime.timedelta object to a string. The resulting string will be in the format "hh:mm:ss. frac_seconds". For example:

import datetime
start = datetime.datetime(2009, 2, 10, 14, 00)
end = datetime.datetime(2009, 2, 10, 16, 00)
delta = end - start
str_duration = str(delta)
print(str_duration)
# prints 2:00:00

You can also use the total_seconds() method to get the total number of seconds in the timedelta object. This can be useful if you want to round the duration to the nearest minute or hour. For example:

rounded_seconds = round(delta.total_seconds())
rounded_minutes = rounded_seconds // 60
rounded_hours = rounded_minutes // 60

The above is the detailed content of How Can I Format a Python `timedelta` Object into a Human-Readable 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