How to subtract hours and minutes from Pandas datetime column?

Use the following syntax to subtract time from a Pandas date column:

hr['your_date_column'] = hr['datetime_column '] -pd.Timedelta(hours = X, minutes = X)

Reduce time from a pandas DataFrame time column

Create DataFrame

Start by importing the pandas library and constructing your DataFrame using this simple Python code:

import pandas as pd
dates = pd.Series(pd.date_range(start='5/1/23', periods=6,freq='B'))
area = ('North', 'South', 'East', 'North', 'West', 'South')
interviews = [13, 12, 8, 9,18, 19]

hr = pd.DataFrame(dict(dates=dates, area = area, interviews =interviews))

Let’s look into our DataFrame columns:

hr.head()

This will render the following:

datesareainterviews
02023-05-01North13
12023-05-02South12
22023-05-03East8
32023-05-04North9
42023-05-05West18
Let’s now check the DataFrame columns data types:
hr.dtypes

This will return the following Series:

dates         datetime64[ns]
area                  object
interviews             int64
dtype: object

The dates column is of type datetime, in the next section we will learn how to subtract or add time to it.

Subtract hours from your date column

We can easily remove time from our dates in Pandas and persist the result in a new created column by using the following code. In our example we will subtract 18 hours from our Date column:

hr['prep_start_dates'] = hr['dates'] - pd.Timedelta(hours = 18)

Looking into our data:

hr.head()
datesareainterviewsprep_start_dates
02023-05-01North132023-04-30 06:00:00
12023-05-02South122023-05-01 06:00:00
22023-05-03East82023-05-02 06:00:00
32023-05-04North92023-05-03 06:00:00
42023-05-05West182023-05-04 06:00:00

Note: You can also use the more idiomatic assign DataFrame method:

hr.assign(prep_start_dates = dates - pd.Timedelta(hours = 9))

Remove minutes from dt column in Pandas

In a similar fashion we can also remove minutes:

hr['prep_start_dates'] = hr['dates'] -pd.Timedelta(hours = 9, minutes = 30)

Or alternatively, using assign:

hr.assign(prep_start_dates = dates - pd.Timedelta(hours = 9, minutes = 30))

Replace your date time column value

You can also replace the content of your original date column with the calculated time:

hr['dates'] = hr['dates'] - pd.Timedelta(hours = 9, minutes = 30)

Adding time to your Pandas column

Adding time to your datetime is also straightforward:

hr['prep_start_dates'] = hr['dates'] + pd.Timedelta(hours = 9, minutes = 30)

Follow up learning

How to create a datetime from a timestamp with Python and Pandas?