How can I subtract 3 hours from a datetime in a Pandas dataframe column?
You can use timedelta
from datetime import timedelta
df['startdate'] = pd.to_datetime(df['startdate']) - timedelta(hours=3)
df['enddate'] = pd.to_datetime(df['enddate']) - timedelta(hours=3)
I believe you need convert columns to_datetime
and subtract 3
hours timedelta:
cols = ['startdate','enddate']
td = pd.Timedelta(3, unit='h')
df[cols] = df[cols].apply(lambda x: pd.to_datetime(x, format='%d/%m/%Y %H:%M:%S') - td
If want aplly solution for each column separately:
td = pd.Timedelta(3, unit='h')
df['startdate'] = pd.to_datetime(df['startdate'], format='%d/%m/%Y %H:%M:%S') - td
df['enddate'] = pd.to_datetime(df['enddate'], format='%d/%m/%Y %H:%M:%S') - td
print (df)
cpf day startdate enddate
0 1234 1 2018-01-08 09:50:00 2018-01-08 12:30:00
1 1234 1 2018-01-08 11:30:00 2018-01-08 12:40:00
2 1234 1 2018-01-08 11:50:00 2018-01-08 12:50:00
3 1234 2 2018-02-08 17:20:00 2018-03-07 21:50:00
4 1234 3 2018-03-07 22:00:00 2018-03-08 00:50:00
5 1235 1 2018-01-08 08:50:00 2018-01-08 12:20:00
6 5212 1 2018-01-08 11:50:00 2018-01-08 12:20:00
Last if need convert datetimes to custom format:
df['startdate'] = df['startdate'].dt.strftime('%d/%m/%Y %H:%M:%S')
df['enddate'] = df['enddate'].dt.strftime('%d/%m/%Y %H:%M:%S')
print (df)
cpf day startdate enddate
0 1234 1 08/01/2018 09:50:00 08/01/2018 12:30:00
1 1234 1 08/01/2018 11:30:00 08/01/2018 12:40:00
2 1234 1 08/01/2018 11:50:00 08/01/2018 12:50:00
3 1234 2 08/02/2018 17:20:00 07/03/2018 21:50:00
4 1234 3 07/03/2018 22:00:00 08/03/2018 00:50:00
5 1235 1 08/01/2018 08:50:00 08/01/2018 12:20:00
6 5212 1 08/01/2018 11:50:00 08/01/2018 12:20:00