Format timedelta as String in Python (3 Examples)

 

This article demonstrates how to format a timedelta object as a string in the Python programming language.

Table of contents:

Let’s start right away.

 

Example Data & Importing Add-Ons

For this tutorial, we need to import the datetime module and the humanize package.

import datetime                                          # loading datetime module
import humanize                                          # loading humanize package

The data below will be used as a basis for this Python tutorial:

td1 = datetime.timedelta(hours=-10)                      # sample timedelta generation 1
td2 = datetime.timedelta(hours=24)                       # sample timedelta generation 2
td3 = datetime.timedelta(days=15, hours=32, seconds=45)  # sample timedelta generation 3
print(td1)                                               # printing td1
# -1 day, 14:00:00
print(td2)                                               # printing td2
# 1 day, 0:00:00
print(td3)                                               # printing td3
# 16 days, 8:00:45

 

Example 1: Convert timedelta to String Data Type

This example demonstrates how to transform the timedelta data type to string.

As a first step, let’s return the current data type of our first data object td1. To achieve this, we can apply the type() function as illustrated below:

print(type(td1))                                         # Check data type of td1
# <class 'datetime.timedelta'>

As shown in the previous output, our data object td1 has the data type datetime.timedelta.

If we want to convert this data type to string, we can employ the str() function as shown in the following code snippet:

td1_str_dtype = str(td1)                                 # Convert timedelta to string
print(td1_str_dtype)                                     # Print updated data object
# -1 day, 14:00:00

The previous line of code has created a new data object called td1_str_dtype. The content of this new data object looks exactly the same as the input data object td1.

However, there is one big difference – the data type! Let’s print the data type using the print() and type() functions:

print(type(td1_str_dtype))                               # Print data type of updated object
# <class 'str'>

Our updated data object has the data type string!

This first example has illustrated how to change the data type from timedelta to string without modifying the content of a data object. However, it’s also possible to insert our timedelta objects into more complex string structures.

You might have guessed it, this is what I’m going to show next!

 

Example 2: User-defined String Formatting Function

The following Python syntax shows how to implement a user-defined function to format a timedelta as a string.

If we need a string in another form (e.g., a report), we can manipulate it via a user-defined function. See timedelta_formatter() below.

def timedelta_formatter(td):                             # defining the function
    td_sec = td.seconds                                  # getting the seconds field of the timedelta
    hour_count, rem = divmod(td_sec, 3600)               # calculating the total hours
    minute_count, second_count = divmod(rem, 60)         # distributing the remainders
    msg = "The time difference is: {} days, {} hours, {} minutes, {} seconds".format(td.days,hour_count,minute_count,second_count)
    return msg                                           # returning the custom output

Here are the outputs for the sample data.

print(timedelta_formatter(td1))                          # printing formatted td1
# The time difference is: -1 days, 14 hours, 0 minutes, 0 seconds
print(timedelta_formatter(td2))                          # printing formatted td2
# The time difference is: 1 days, 0 hours, 0 minutes, 0 seconds
print(timedelta_formatter(td3))                          # printing formatted td3
# The time difference is: 16 days, 8 hours, 0 minutes, 45 seconds

 

Example 3: naturaltime() Function of humanize Package

The following Python code illustrates how to utilize the humanize package for formatting timedelta objects as strings. The package helps with converting timedelta objects to phrases in English. The only downside is that it returns an approximation of the time, which lacks in detail. Please compare the output below with the ones above.

print(humanize.naturaltime(td1))                         # printing humanized td1
# 10 hours from now
 
print(humanize.naturaltime(td2))                         # printing humanized td2
# a day ago
 
print(humanize.naturaltime(td3))                         # printing humanized td3
# 16 days ago

 

Video & Further Resources

I have recently published a video on my YouTube channel, which demonstrates the Python programming code of this article. You can find the video below:

 

The YouTube video will be added soon.

 

Furthermore, you could have a look at the related articles on this homepage.

 

Summary: In this article, I have demonstrated how to modify the display of timedelta objects in Python programming. In case you have further questions, please let me know in the comments. Furthermore, don’t forget to subscribe to my email newsletter to get updates on the newest articles.

 

Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get additional information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top