Python Subtract Hours from Datetime Example

By Hardik Savani October 30, 2023 Category : Python

This is a short guide on python subtract hours to time example. if you have question about how to subtract hours to datetime in python then I will give simple example with solution. Here you will learn how to subtract hour to current date in python. it's simple example of python minus hours to time in dataframe. Alright, let’s dive into the steps.

In this example, I will give two examples for you of how to subtract hours to datetime in python and how to subtract hours to today's time in python. therefore, let's see below example code and try it.

You can use these examples with python3 (Python 3) version.

Example 1: Python Subtract Hours to DateTime

main.py

from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDateString = "2022-06-01"
  
myDate = datetime.strptime(myDateString, "%Y-%m-%d")
  
subHoursNumber = 2;
newDate = myDate - relativedelta(hours=subHoursNumber)
  
print("Old Date :")
print(myDate)
  
print("New Date :")
print(newDate)

Output:

Old Date :
2022-06-01 00:00:00
New Date :
2022-05-31 22:00:00

Example 2: Python Subtract Hours to Current DateTime

main.py

from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDate = datetime.today()
    
subHoursNumber = 2;
newDate = myDate - relativedelta(hours=subHoursNumber)
 
print("Old Date :")
print(myDate)
  
print("New Date :")
print(newDate)

Output:

Old Date :
2022-06-17 09:20:00.447360
New Date :
2022-06-17 07:20:00.447360

I hope it can help you...

Tags :
Shares