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.
- Dates & Times in Python – datetime Module
- Introduction to timedelta Objects in Python
- Convert Integer to String in pandas DataFrame Column in Python
- Convert Float to String in pandas DataFrame Column in Python
- Convert Object Data Type to String in pandas DataFrame Column in Python
- Convert String to Boolean in pandas DataFrame Column in Python
- Introduction to Python Programming
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.
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.