How to Add Hours to Date in Python?

How to Add Hours to Date in Python?

In this article we will learn about How to Add Hours to Date in Python?

Example 1:

from datetime import datetime
from dateutil.relativedelta import relativedelta

myDateString ="2022-07-25"

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-25 00:00:00
New Date :
2022-07-25 02:00:00

Example 2 : Python Add Hours to Current Date

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)
Old Date :
2022-07-25 07:40:10.343233
New Date :
2022-07-25 09:40:10.343233

Also Read :