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

Using Python how can I floor a DateTime value by a custom amount?

I have a CSV with Date and Time columns, I combine them in pandas dataframe with the format ‘%d/%m/%Y %H:%M’ and I’ve been using floor from datetime package to set any time to the hour:

df['DateTime'] = df['DateTime'].dt.floor('H')

Instead I want to floor every 6 hours such that ’08/09/2022 8:46′ becomes ’08/09/2022 6:00′ or ’08/09/2022 23:59′ becomes ’08/09/2022 18:00′ or another custom time period

Similarly, would it be possible to offset where the floor begins? e.g. if we set the floor to start at 1:00 then 0:59 becomes 19:00 instead of 0:00.

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

How can I edit the function to achieve this?

>Solution :

Use '6H' as frequency in floor:

df = pd.DataFrame({'DateTime': ['08/09/2022 8:46',  '08/09/2022 23:59', '08/09/2022 00:59']})
df['DateTime'] = pd.to_datetime(df['DateTime'])

df['DateTime'].dt.floor('6H')

Output:

0   2022-08-09 06:00:00
1   2022-08-09 18:00:00
2   2022-08-09 00:00:00
Name: DateTime, dtype: datetime64[ns]

To shift by 1 hour, subtract 1 hour:

df['DateTime'].sub(pd.Timedelta('1h')).dt.floor('6H')

Output:

0   2022-08-09 06:00:00
1   2022-08-09 18:00:00
2   2022-08-08 18:00:00
Name: DateTime, dtype: datetime64[ns]
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