Convert String to timedelta in Python (Example)

 

In this Python programming tutorial, you’ll learn how to convert a string to a timedelta object.

The tutorial will contain these topics:

Let’s do this.

 

Example Data & Imported Modules

Initially, we should import the datetime module.

import datetime                                      # Load datetime module

As a next step, we should construct data to be used in the next example:

str_td = "13:42:10"                                  # Sample timedelta as a string

 

Example: Converting string to timedelta by strptime()

This example shows how to create a timedelta object from a string using the strptime() function.

First, we will create a datetime object via the strptime() function.

dt = datetime.datetime.strptime(str_td, "%H:%M:%S")  # string to datetime conversion
print(dt)                                            # print datetime
# 1900-01-01 13:42:10

Afterwards, we will calculate the total count of seconds to be used for creating the timedelta object.

total_sec = dt.hour*3600 + dt.minute*60 + dt.second  # total seconds calculation
td = datetime.timedelta(seconds=total_sec)           # timedelta construction
print(td)                                            # print timedelta
# 13:42:10

 

Video, Further Resources & Summary

If you need further explanations on the Python code of this article, I recommend having a look at the following video on my YouTube channel. In the video, I’m explaining the topics of this tutorial:

 

The YouTube video will be added soon.

 

Besides that, you may have a look at the other Python tutorials on this homepage. You can find a selection of articles on similar topics such as data objects, character strings, and data conversion below.

 

Summary: At this point, you should know how to generate a timedelta object from a string in the Python programming language. Please let me know in the comments section, if you have any further questions or comments.

 

Ömer Ekiz Python Programming & Informatics

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

 

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.

The maximum upload file size: 2 MB. You can upload: image. Drop file here

Top