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
Release: 2024-12-28 17:53:10
Original
256 people have browsed it

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

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

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!

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