Home > Enterprise >  Adjusting datetime in pandas dataframe based on multiple conditions
Adjusting datetime in pandas dataframe based on multiple conditions

Time:06-13

I have a pandas dataframe with a list of datetimes in them. I want to add 12 hours onto any date time that is not equal to 8am and but is still in the morning. For example:

Datetime A
2022-01-01 08:00:00 10
2022-01-01 09:00:00 10
2022-01-01 12:00:00 10
2022-01-01 24:00:00 10

Should become:

Datetime A
2022-01-01 08:00:00 10
2022-01-01 21:00:00 10
2022-01-01 12:00:00 10
2022-01-01 24:00:00 10

I can do this by looping through the dataframe one element at a time and doing this conditional check. However, the dataset I am working with is large. Is it possible to do this without looping though the whole dataset by filtering on this condition. So far I have not managed to find a way!

CodePudding user response:

I just write some code. You can utilize .dt.hour and datetime.timedelta to solve this problem

import datetime

data = """2022-01-01 08:00:00   10
2022-01-01 09:00:00 10
2022-01-01 12:00:00 10
2022-01-01 23:00:00 10"""

data = [f.split("\t") for f in data.split("\n")]

df = pd.DataFrame(data=data, columns=['Datetime', 'A'])

df['Datetime'] = pd.to_datetime(df['Datetime'])
mask = (df['Datetime'].dt.hour != 8) & (df['Datetime'].dt.hour <=12)

df.loc[mask, "Datetime"]  = datetime.timedelta(hours=12)
  • Related