Python Subtract Hours from Datetime Example

Python Subtract Hours from Datetime Example

In this article we will learn about Python Subtract Hours from Datetime Example.


Example 1 : Python Subtract Hours to Date Time

from datetime import datetime
from dateutil.relativedelta import relativedelta

myDateString ="2022-07-26"

myDate = datetime.strptime(myDateString, "%Y-%m-%d")

addHourNumber =2;
newDate = myDate - relativedelta(hours=addHourNumber)

print("Old Date :")
print(myDate)

print("New Date :")
print(newDate)

Output :

Old Date :
2022-07-02 00:00:00

New Date :
2022-07-01 22:00:00


Example 2 : Python Subtract Hours to Current Date Time

from datetime import datetime
from dateutil.relativedelta import relativedelta

myDate =datetime.today()

addHourNumber =2;
newDate = myDate - relativedelta(hours=addHourNumber)

print("Old Date :")
print(myDate)

print("New Date :")
print(newDate)

Output :

Old Date :
2022-07-26 07:01:00.454509

New Date :
2022-07-26 05:01:00.454509


Also Read :