Python pandas : add one hour to a Dataframe column containing dates

92 Views Asked by At

I am new at python.
I have a df called dates which is storing dates. I want to add an extra hour to the whole column.

0       2011-01-07
1       2011-01-07
2       2011-01-10
3       2011-01-10
4       2011-01-10
Name: dates, Length: 15644, dtype: datetime64[ns]

This is the code I want to apply on it

from datetime import datetime , timedelta

timestamp = pd.Timestamp('2023-01-01 12:00')
new_timestamp = timestamp + timedelta(days=0, hours=1)

The code works fine on its own but how can I apply these functions on my df which is stored as a pandas series?

Please help. Thanks!!!

1

There are 1 best solutions below

5
Nauel On

As far as I understood you want to, given a certain column filled with dates, add an hour to each observation.

With timedelta and a lambda function you can do the following:

import pandas as pd
from datetime import timedelta

dates = pd.DataFrame({'dates': ['2011-01-07', '2011-01-07', '2011-01-10', '2011-01-10', '2011-01-10']})
dates['dates'] = pd.to_datetime(dates['dates'])

# Add Hours to the format
dates['dates'] = dates['dates'].dt.strftime('%Y-%m-%d %H')

print(dates.head().to_markdown())

Result:

|    | dates         |
|---:|:--------------|
|  0 | 2011-01-07 00 |
|  1 | 2011-01-07 00 |
|  2 | 2011-01-10 00 |
|  3 | 2011-01-10 00 |
|  4 | 2011-01-10 00 |