How To Add Hours To Datetime In Python

Add hours to datetime in Python

To add hours to datetime in Python, you can use the pandas library or timedelta class. Let follow the article to better understand.

Add hours to datetime in Python

In Python, datetime module determines the date and time with the timestamps.

Example:

import datetime

timeNow = datetime.datetime.now()
print(timeNow)

Output:

2022-10-05 12:57:39.400159

To add hours to datetime, we have the following ways:

Use pandas library 

Pandas is a library in Python that provides powerful and flexible data structures and networks. The Pandas library provides a DateOffset class to store time and interval information. It is also used with the datetime module to add N hours to the datetime.

Example:

  • Create the current time period.
  • Adding N hours using the DateOffset class.
import pandas as pd
import datetime

timeNow = datetime.datetime.now()
print(timeNow )
n = 10

# Add 10 hours to the datetime object
timeAfterAdding = timeNow + pd.DateOffset(hours=n)
print('Time after adding (10 hours after given time ): ', timeAfterAdding)

Output:

2022-10-06 04:48:21.228201
Time after adding (10 hours after given time ): 2022-10-06 14:48:21.228201

Use timedelta class

Python has a datetime module that works with and handles dates and timestamps. In that datetime module there are classes like datetime.date, datetime.time, datetime.datetime and datetime.delta. To add N hours from the current datatime I will use datetime.timedelta class.

Example:

  • Create the current time period.
  • Adding N hours using the datetime.timedelta class.
import datetime
from datetime import timedelta

timeNow = datetime.datetime.now()
print(timeNow )
n = 10

# Add 10 hours to the datetime object
timeAfterAdding = timeNow + timedelta(hours=n)
print('Time after adding (10 hours after given time ): ', timeAfterAdding)

Output:

2022-10-06 05:02:44.414433
Time after adding (10 hours after given time ): 2022-10-06 15:02:44.414433

Use the relativedelta class

The dateutil module in Python provides a relativedelta class that you can use to add N hours from the current time period.

Example:

  • Create the current time period.
  • Adding N hours using the relativedelta class.
import datetime
from dateutil.relativedelta import relativedelta

timeNow = datetime.datetime.now()
print(timeNow)
n = 10
 
# Add 10 hours to the datetime object
timeAfterAdding= timeNow + relativedelta(hours=n)
print('Time after adding (10 hours after given time ): ', timeAfterAdding)

Output:

2022-10-06 05:10:32.017016
Time after adding (10 hours after given time ): 2022-10-06 15:10:32.017016

Summary

If you have any questions about how to add hours to datetime in Python, leave a comment below. I will support your questions. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *