Get N Hours, Minutes & Seconds Earlier as datetime Object in Python (3 Examples)

In this Python tutorial, you’ll learn how to subtract a specific number of seconds, minutes, and hours from a datetime object in the Python programming language.

Preparing the Examples

import datetime                                          # Load datetime

The data below will be used for the examples of this article:

datetime_x = datetime.datetime(2022, 4, 12, 22, 28, 45)  # Construct datetime object
print(datetime_x)
# 2022-04-12 22:28:45

Example 1: Subtract N Hours from datetime object

Before we can subtract a certain amount of hours, minutes, or seconds from our datetime object, we need to import the timedelta() function:

from datetime import timedelta                           # Load timedelta

To get the time N hours ago, we can apply the timedelta() function in combination with the hours argument:

datetime_x_hrs = datetime_x - timedelta(hours = 5)       # Get 5 hours ago
print(datetime_x_hrs) 
# 2022-04-12 17:28:45

Example 2: Subtract N Minutes from datetime object

To subtract minutes from our datetime object, we use the timedelta() function combined with the minutes argument.

datetime_x_min = datetime_x - timedelta(minutes = 35)    # Get 35 minutes ago
print(datetime_x_min) 
# 2022-04-12 21:53:45

Example 3: Subtract N Seconds from datetime object

And for subtracting N seconds from the datetime object, we apply the timedelta() function within the seconds argument:

datetime_x_sec = datetime_x - timedelta(seconds = 20)    # Get 20 seconds ago
print(datetime_x_sec) 
# 2022-04-12 22:28:25

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.

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