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!