Convert timedelta to datetime Object in Python (Example)
In this Python tutorial you’ll learn how to convert timedelta objects to datetime objects.
The tutorial consists of one example for illustrating the transformation from timedelta objects to datetime objects. The content of the tutorial is structured as follows:
So now is the part you have been waiting for!
Example Data & Imported Modules
For this example, we need to import the datetime module and define a timedelta object, which is td in this case.
import datetime # Loading datetime module td = datetime.timedelta(days=45, seconds=500000) # instantiating timedelta object print(td) # printing the timedelta object # 50 days, 18:53:20
As seen in the previous output, td is formatted by the print() function automatically.
Let’s create an example now!
Example: Converting timedelta to datetime
Since timedelta objects refer to the diffference between two datetime objects, we need another datetime object as a reference. It is defined under the name dt_origin as follows.
dt_origin = datetime.datetime(1995, 5, 1, 14, 15, 3) # instantiating origin datetime object print(dt_origin) # printing the datetime object # 1995-05-01 14:15:03
Now we are ready to implement the conversion!
dt_new = dt_origin + td # generating a datetime from timedelta object print(dt_new) # printing the generated datetime object # 1995-06-21 09:08:23
Video & Further Resources
Have a look at the following video on my YouTube channel. In the video, I demonstrate the Python codes of this article.
The YouTube video will be added soon.
In addition, you may have a look at some of the other tutorials on statisticsglobe.com:
- Dates & Times in Python – datetime Module
- Introduction to timedelta Objects in Python
- Convert datetime Object to Date Only String in Python
- Convert datetime Object to Seconds, Minutes & Hours in Python
- Convert datetime Object to Local Time Zone in Python
- Convert Epoch Time to datetime Object & Vice Versa in Python
- All Python Programming Tutorials
At this point you should have learned how to create datetime objects from timedelta objects in Python. Let me know in the comments, in case you have any further questions.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.