How to Subtract Hours from Datetime in Python?
Published On: 09/09/2022 | Category:
Python

Hi Guys,
This article will provide example of python 3 subtract hours to time string. it's simple example of how to subtract hours to datetime in python. This article will give you simple example of how to subtract hour to current date in python. this example will help you python subtract 1 hour to datetime string.
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.
So let's see bellow example:
Example 1: Python Subtract Hours to DateTime main.pyfrom datetime import datetime from dateutil.relativedelta import relativedelta myDateString = "2022-09-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-09-01 00:00:00 New Date : 2022-08-31 22:00:00Example 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-09-09 04:28:59.917025 New Date : 2022-09-09 02:28:59.917025
It will help you....
Happy Coding!