Add hours to datetime in Python

In this article, we will discuss different ways to add hours to a given timestamp in python using timedelta, pandas or relativedelta.

Suppose you have a timestamp as string and you want to add N hours to it, where N can be any number. But you want the final timestamp after adding N hours, in the given string format. Let’s see how to do that,

Add hours to a timestamp in Python using timedelta

Python provides a module datetime for manipulation of date and time. It consists of following classes,

  • datetime.date: An object of date class specifies a date using year, month and day.
  • datetime.time: An object of time class specifies a timestamp using hour, minute, second, microsecond, and tzinfo.
  • datetime.datetime: An object of datetime is a combination of a date and a time.
  • datetime.timedelta: A duration, that represents the difference between two dates or times or datetimes.
  • datetime.tzinfo: It contains the timezone information.

To add hours in a given timestamp, we are going to use the datetime and timedelta classes of the datetime module.

Steps to add N hours to datetime are as follows,

  • Step 1: If the given timestamp is in a string format, then we need to convert it to the datetime object. For that we can use the datetime.strptime() function. Whereas, if the given timestamp is already a datetime object, then you can skip this step.
  • Step 2: Create an object of timedelta, to represent an interval of N hours. For that, pass the argument hours with value N in the timedelta constructor.
  • Step 3: Add the timedelta object to the datetime object. It will give us a new datetime object, pointing to a new timestamp i.e. N hours after the given timestamp.
  • Step 4: If you want the final timestamp in string format, then convert the datetime object to string using strftime(). You can pass the format string as argument and it will convert the datetime object to a string of the specified format.

Let’s understand with an example,

Add 2 hours to a timestamp in python

from datetime import datetime
from datetime import timedelta

# Given timestamp in string
time_str = '24/7/2021 11:13:08.230010'
date_format_str = '%d/%m/%Y %H:%M:%S.%f'

# create datetime object from timestamp string
given_time = datetime.strptime(time_str, date_format_str)

print('Given Time: ', given_time)

n = 2
# Add 2 hours to datetime object
final_time = given_time + timedelta(hours=n)

print('Final Time (2 hours after given time ): ', final_time)

# Convert datetime object to string in specific format 
final_time_str = final_time.strftime('%d/%m/%Y %H:%M:%S.%f')
print('Final Time as string object: ', final_time_str)

Output

Given Time:  2021-07-24 11:13:08.230010
Final Time (2 hours after given time ):  2021-07-24 13:13:08.230010
Final Time as string object:  24/07/2021 13:13:08.230010

We added 2 hours to the timestamp ’24/7/2021 11:13:08.230010′ to make it ’24/07/2021 13:13:08.230010′.

As we added a timedelta (of 2 hours duration) to the datetime object, so it returned a new datetime object pointing to the new timestamp. Then we converted the datetime object to the required string format using datetime.strftime(). If your timestamp string is of some other format, then you can change the format according to that while using strptime() & strftime().

Add hours to given timestamp in Python using Pandas

Pandas provide a class DateOffset, to store the duration or interval information. It is mostly used to increment or decrement a timestamp. It can be used with datetime module to add N hours to a datetime. Let’s understand with an example,

Add 3 hours to a datetime in python

from datetime import datetime
import pandas as pd

# Given timestamp in string
time_str = '24/7/2021 11:13:08.230010'
date_format_str = '%d/%m/%Y %H:%M:%S.%f'

# create datetime object from timestamp string
given_time = datetime.strptime(time_str, date_format_str)

print('Given Time: ', given_time)

n = 3
# Add 3 hours to datetime object
final_time = given_time + pd.DateOffset(hours=n)

print('Final Time (3 hours after given time ): ', final_time)

# Convert datetime object to string in specific format 
final_time_str = final_time.strftime('%d/%m/%Y %H:%M:%S.%f')
print('Final Time as string object: ', final_time_str)

Output

Given Time:  2021-07-24 11:13:08.230010
Final Time (3 hours after given time ):  2021-07-24 14:13:08.230010 
Final Time as string object:  24/07/2021 14:13:08.230010

We created a DateOffset object by passing hours argument as 3. Then we added this DateOffset object to the datetime object. It returned a new datetime object pointing to a new timestamp i.e. after 3 hours from the given timestamp.

Add hours to given timestamp in python using relativedelta

In python, the dateutil module provides a class relativedelta, which represents an interval of time. The relativedelta class has all the attributes to represent a duration i.e. Year, Month, Day, Hours, Minutes, Seconds and Microseconds.

So, to add hours to a given timestamp, we can create a relativedelta object to represents the interval in hours and then add it to the datetime object containing give date. Let’s understand with an example,

Add 30 hours to a timestamp in python

from datetime import datetime
from dateutil.relativedelta import relativedelta

# Given timestamp in string
time_str = '24/7/2021 11:13:08.230010'
date_format_str = '%d/%m/%Y %H:%M:%S.%f'

# create datetime object from timestamp string
given_time = datetime.strptime(time_str, date_format_str)

print('Given Time: ', given_time)

n = 30
# Add 3 hours to datetime object
final_time = given_time + relativedelta(hours=n)

print('Final Time (30 hours after given time ): ', final_time)

# Convert datetime object to string in specific format 
final_time_str = final_time.strftime('%d/%m/%Y %H:%M:%S.%f')
print('Final Time as string object: ', final_time_str)

Output

Given Time:  2021-07-24 11:13:08.230010
Final Time (30 hours after given time ):  2021-07-25 17:13:08.230010
Final Time as string object:  25/07/2021 17:13:08.230010

As given timestamp was in string, so first we converted it to the datetime object. After that we created a relativedelta object representing 30 hours by passing hours argument as 30. Then added that to the datetime object. It returned a new datetime object pointing to a new timestamp i.e. thirty hours after the given timestamp.

Summary:

We learned about three different ways to add N hours to a timestamp in python.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top