How to Specify String Format for Timedelta in Python?

Estimated read time 1 min read

In Python, you can use the strftime() method to format a timedelta object as a string. The strftime() method works similarly to the strftime() method for datetime objects, but with some differences in the available format codes.

Here’s an example of how to use strftime() to format a timedelta object:

from datetime import timedelta

delta = timedelta(days=5, hours=3, minutes=20)

formatted_delta = "{0} days, {1} hours, {2} minutes".format(delta.days, delta.seconds // 3600, (delta.seconds // 60) % 60)


In this example, we create a timedelta object representing 5 days, 3 hours, and 20 minutes. We then use the days, seconds, and microseconds attributes of the timedelta object to extract the individual components of the time delta. We use these components to format the timedelta object as a string using the format() method.

Note that there is no direct way to format a timedelta object using strftime() because it does not have a year or month component, which are required by some of the format codes used by strftime(). You can use the individual components of the timedelta object to create a custom string representation of the time delta, as shown in the example above.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply