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:
dates | area | interviews | |
---|---|---|---|
0 | 2023-05-01 | North | 13 |
1 | 2023-05-02 | South | 12 |
2 | 2023-05-03 | East | 8 |
3 | 2023-05-04 | North | 9 |
4 | 2023-05-05 | West | 18 |
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()
dates | area | interviews | prep_start_dates | |
---|---|---|---|---|
0 | 2023-05-01 | North | 13 | 2023-04-30 06:00:00 |
1 | 2023-05-02 | South | 12 | 2023-05-01 06:00:00 |
2 | 2023-05-03 | East | 8 | 2023-05-02 06:00:00 |
3 | 2023-05-04 | North | 9 | 2023-05-03 06:00:00 |
4 | 2023-05-05 | West | 18 | 2023-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?