Subtract hours from current time in Python

In this article, we will discuss different ways to subtract hours from current time in python using timedelta, pandas or relativedelta.

Subtract hours from current time in Python using timedelta

Python provides a module datetime for manipulation of date and time. It consists of following classes,

  • datetime.date: An object of date class specifies a date using year, month and day.
  • datetime.time: An object of time class specifies a timestamp using hour, minute, second, microsecond, and tzinfo.
  • datetime.datetime: An object of datetime is a combination of a date and a time.
  • datetime.timedelta: A duration, that represents the difference between two dates or times or datetimes.
  • datetime.tzinfo: It contains the timezone information.

To subtract few hours from current time, we are going to use the datetime and timedelta classes of the datetime module.

Steps to subtract N hours to datetime are as follows,

  • Step 1: Get the current time in python using datetime.now(). It returns a datetime object pointing to the current time in local timezone.
  • Step 2: Create an object of timedelta, to represent an interval of N hours. For that, pass the argument hours with value N in the timedelta constructor.
  • Step 3: Subtract the timedelta object from the datetime object pointing to current time. It will give us a new datetime object, pointing to a new timestamp in past i.e. N hours ago from now.
  • Step 4: If you want the final timestamp in string format, then convert the datetime object to string using strftime(). You can pass the format string as argument and it will convert the datetime object to a string of the specified format.

Let’s understand with an example,

Subtract 2 hours from current time in python

from datetime import datetime
from datetime import timedelta

# Get current time in local timezone
current_time = datetime.now()
print('Current Time: ', current_time)

n = 2
# Subtract 2 hours from datetime object containing current time
past_time = current_time - timedelta(hours=n)

print('Past Time (2 hours ago): ', past_time)

# Convert datetime object to string in specific format 
past_time_str = past_time.strftime('%m-%d-%Y %H:%M:%S.%f')
print('Past Time as string object: ', past_time_str)

Output

Current Time:  2021-06-19 22:57:09.436770
Past Time (2 hours ago):  2021-06-19 20:57:09.436770   
Past Time as string object:  06-19-2021 20:57:09.436770

First we fetched the current time using datetime.now() function and then subtracted 2 hours from the current time using timedelta. It gave us a new datetime object, pointing to a past timestamp i.e. 2 hours ago from now. Then we converted the datetime object to the required string format using datetime.strftime(). If your timestamp string is of some other format, then you can change the format according to that while using strptime() & strftime().

Subtract hours from current time in Python using Pandas

Pandas provide a class DateOffset, to store the duration or interval information. It is mostly used to increment or decrement a timestamp. It can be used with datetime module to subtract N hours from current time. Let’s understand with an example,

Subtract 2 hours from current time in python using pandas

from datetime import datetime
import pandas as pd

# Get current time in local timezone
current_time = datetime.now()
print('Current Time: ', current_time)

n = 2
# Subtract 2 hours from datetime object containing current time
past_time = current_time - pd.DateOffset(hours=n)

print('Past Time (2 hours ago): ', past_time)

# Convert datetime object to string in specific format 
past_time_str = past_time.strftime('%m-%d-%Y %H:%M:%S.%f')
print('Past Time as string object: ', past_time_str)

Output

Current Time:  2021-06-19 22:57:12.377734
Past Time (2 hours ago):  2021-06-19 20:57:12.377734   
Past Time as string object:  06-19-2021 20:57:12.377734

We created a DateOffset object by passing hours argument as 2. Then we subtracted this DateOffset object to the datetime object pointing to the current time. It returned a new datetime object pointing to the past timestamp i.e. 2 hours ago from now.

Subtract hours from current time in python using relativedelta

In python, the dateutil module provides a class relativedelta, which represents an interval of time. The relativedelta class has all the attributes to represent a duration i.e. Year, Month, Day, Hours, Minutes, Seconds and Microseconds.

So, to subtract hours to a current time, we can create a relativedelta object to represents the interval in hours and then subtract it from the datetime object containing the current time. Let’s understand with an example,

Subtract 2 hours to current time in python using relativedelta

from datetime import datetime
from dateutil.relativedelta import relativedelta

# Get current time in local timezone
current_time = datetime.now()
print('Current Time: ', current_time)

n = 2
# Subtract 2 hours from current time
past_time = current_time - relativedelta(hours=n)

print('Past Time (2 hours ago): ', past_time)

# Convert datetime object to string in specific format 
past_time_str = past_time.strftime('%m-%d-%Y %H:%M:%S.%f')
print('Past Time as string object: ', past_time_str)

Output

Current Time:  2021-06-19 22:57:12.377734
Past Time (2 hours ago):  2021-06-19 20:57:12.377734   
Past Time as string object:  06-19-2021 20:57:12.377734

We fetched the current timestamp as datetime object using datetime.now(). Then we created a relativedelta object representing 2 hours by passing hours argument as 2. Then subtracted that to the datetime object. It returned a new datetime object pointing to a past timestamp i.e. two hours ago from now.

Summary:

We learned about three different ways to subtract N hours from current time in python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top