Add Hours, Minutes & Seconds to datetime Object in Python (3 Examples)
This article explains how to add hours, minutes, and seconds to datetime objects in the Python programming language.
Creating Example Data & Loading datetime Module
We can load the datetime module as shown below.
import datetime |
import datetime
For the examples of this tutorial, we will use the data below.
x = datetime.datetime(2024, 8, 12, 18, 52, 8) print(x) # 2024-08-12 18:52:08 |
x = datetime.datetime(2024, 8, 12, 18, 52, 8) print(x) # 2024-08-12 18:52:08
Example 1: Add Hours to a Datetime Object
To add additional hours to a datetime object we can use the timedelta function.
x_h = x + datetime.timedelta(hours = 50) print(x_h) # 2024-08-14 20:52:08 |
x_h = x + datetime.timedelta(hours = 50) print(x_h) # 2024-08-14 20:52:08
Example 2: Add Minutes to a Datetime Object
The code below adds minutes to the datetime object.
x_min = x + datetime.timedelta(minutes = 21) print(x_min) # 2024-08-12 19:13:08 |
x_min = x + datetime.timedelta(minutes = 21) print(x_min) # 2024-08-12 19:13:08
Example 3: Add Seconds to a Datetime Object
With the timedelta function, we can also add seconds to the datetime object in Python.
x_sec = x + datetime.timedelta(seconds = 40) print(x_sec) # 2024-08-12 18:52:48 |
x_sec = x + datetime.timedelta(seconds = 40) print(x_sec) # 2024-08-12 18:52:48
Further Resources
Please find some related tutorials below.
- Transform datetime Object to Hours Minutes or Seconds in Python (3 Examples)
- Transform datetime into String with Milliseconds in Python (3 Examples)
- Get Time Difference Between Two Dates & Times in Python (datetime Module)
- Transform datetime to String without Microsecond Component in Python (3 Examples)
- All Python Programming Tutorials
Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.