How to Convert timedelta
Objects to Strings in Python
Python's datetime.timedelta
objects represent durations – the difference between two dates or times.
This guide explains how to convert timedelta
objects into human-readable string representations, covering built-in string conversion, custom formatting, and the humanize
library.
Basic String Conversion with str()
The simplest way to get a string representation of a timedelta
object is to use the built-in str()
function:
from datetime import datetime, timedelta
start_datetime = datetime(2023, 9, 20, 8, 30)
end_datetime = datetime(2023, 9, 30, 10, 30)
time_delta = end_datetime - start_datetime
print(time_delta) # Output: 10 days, 2:00:00
print(type(time_delta)) # Output: <class 'datetime.timedelta'>
time_delta_str = str(time_delta)
print(time_delta_str) # Output: 10 days, 2:00:00
print(type(time_delta_str)) # Output: <class 'str'>
str(time_delta)
: This directly converts thetimedelta
object to its default string representation. The format is generally[D day[s], ][H]H:MM:SS[.UUUUUU]
, where:D
is the number of days (optional, only present if non-zero).H
is the number of hours (0-23).MM
is the number of minutes (00-59).SS
is the number of seconds (00-59).UUUUUU
represents the microseconds.
You can also use f-strings to include the timedelta in a string directly:
from datetime import datetime
start_datetime = datetime(2023, 9, 20, 8, 30)
end_datetime = datetime(2023, 9, 30, 10, 30)
time_delta = end_datetime - start_datetime
result = f'{time_delta} hours ago'
print(result) # Output: 10 days, 2:00:00 hours ago
- f-strings will implicitly convert the value of
time_delta
to a string.
To remove the microseconds, use string slicing:
from datetime import datetime
start_datetime = datetime(2023, 9, 20, 8, 30, 15, 453000)
end_datetime = datetime(2023, 9, 30, 10, 30, 15, 421000)
time_delta = end_datetime - start_datetime
print(time_delta) # Output: 10 days, 1:59:59.968000
print(type(time_delta)) # Output: <class 'datetime.timedelta'>
time_delta = str(time_delta)
time_delta = time_delta.split('.', maxsplit=1)[0]
print(time_delta) # Output: 10 days, 1:59:59
Custom Formatting of timedelta
Objects
For more control over the output format, you can extract the individual components of the timedelta
object (days, seconds, microseconds) and format them yourself:
from datetime import datetime
start_datetime = datetime(2023, 9, 20, 8, 30, 40)
end_datetime = datetime(2023, 9, 30, 10, 30, 50)
time_delta = end_datetime - start_datetime
total_seconds = time_delta.total_seconds() # Get total seconds
print(total_seconds)
hours, remainder = divmod(total_seconds, 60 * 60) # Get hours and remaining seconds
minutes, seconds = divmod(remainder, 60) # Get minutes and remaining seconds
time_delta_string = f'{int(hours):02}:{int(minutes):02}:{int(seconds):02}' # Format using f-string
print(time_delta_string) # Output: 02:00:10
time_delta.total_seconds()
: Gets the total duration in seconds (as a float).divmod(total_seconds, 3600)
: Calculates the number of whole hours and the remaining seconds.divmod(remainder, 60)
: Calculates the number of whole minutes and the remaining seconds.f'{hours:02}:{minutes:02}:{seconds:02}'
: Uses an f-string to format the output with leading zeros. The:02
ensures each component is two digits wide.
You can also create a reusable function that takes timedelta
object as a parameter:
from datetime import datetime, timedelta
def td_format(td_object: timedelta) -> str: # Added type hints.
"""Formats a timedelta object to a string 'DD days, HH:MM:SS'."""
seconds = int(td_object.total_seconds())
periods = [
('year', 60*60*24*365),
('month', 60*60*24*30),
('day', 60*60*24),
('hour', 60*60),
('minute', 60),
('second', 1)
]
strings = []
for period_name, period_seconds in periods:
if seconds >= period_seconds:
period_value, seconds = divmod(seconds, period_seconds)
has_s = 's' if period_value > 1 else ''
strings.append(f"{period_value} {period_name}{has_s}")
return ", ".join(strings)
start_datetime = datetime(2023, 9, 20, 8, 30, 40)
end_datetime = datetime(2023, 9, 30, 10, 30, 50)
time_delta = end_datetime - start_datetime
print(td_format(time_delta)) # Output: 10 days, 2 hours, 0 minutes, 10 seconds
Using the humanize
Library (for Natural Language)
The humanize
library provides functions for creating human-readable representations of times, dates, numbers, and more. Install it with pip install humanize
.
from datetime import datetime, timedelta
import humanize
start_datetime = datetime(2023, 9, 20, 8, 30, 40, 5000)
end_datetime = datetime(2023, 9, 30, 10, 30, 50, 3000)
time_delta = end_datetime - start_datetime
print(humanize.naturaltime(time_delta))
# Output: 10 days ago
print(humanize.precisedelta(time_delta))
# Output: 10 days, 2 hours, 0 minutes, and 9.99 seconds
print(humanize.precisedelta(time_delta, minimum_unit="microseconds"))
# Output: 10 days, 2 hours, 0 minutes, 9 seconds, and 998000 microseconds
print(humanize.precisedelta(time_delta, suppress=["days"], format="%0.4f"))
# Output: 242 hours and 0.0010 seconds
humanize.naturaltime()
: Gives a natural language representation (e.g., "2 hours ago", "in 3 days").humanize.precisedelta()
: Provides a more precise human-readable duration (e.g., "2 hours, 5 minutes, 10 seconds"). You can customize the output format.