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?

To add hours to a date in Python, you can use the datetime module. Here’s an example code snippet that demonstrates how to add hours to a date:


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

In this code, we first import the datetime module and the timedelta class, which allows us to create time durations. We then create a datetime object representing the current date and time using the now() method.

To add hours to the datetime, we create a new timedelta object with addHoursNumbers =2 and add it to the original datetime using the + operator. The result is a new datetime object with 2 hours added to the original datetime.

Finally, we print both the original datetime and the new datetime using the print() function. You can modify the code to add a different number of hours or to work with a specific date and time instead of the current datetime.


Also Read :