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

Question:

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.

How can I edit the function to achieve this?

Asked By: coghlan

||

Answers:

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]
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.