Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adjusting datetime in pandas dataframe based on multiple conditions

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading