How to Add Hours to Date in Python?

By Hardik Savani October 30, 2023 Category : Python

This tutorial shows you python add hours to date example. I would like to show you how to add hours to date in python. We will use how to add hour to current date in python. I would like to show you python add hours to date in dataframe.

In this example, I will give two examples for you of how to add hours to date in python and how to add hours to today's date 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 Add Hours to Date

main.py

from datetime import datetime
from dateutil.relativedelta import relativedelta
  
myDateString = "2022-06-01"
    
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-06-01 00:00:00
New Date :
2022-06-01 02:00:00

Example 2: Python Add Hours to Current Date

main.py

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-06-16 09:50:04.268558
New Date :
2022-06-16 11:50:04.268558

I hope it can help you...

Tags :
Shares