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

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

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

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

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

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

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.

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.
You need to agree with the terms to proceed

Menu
Top