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

How can I move datetime to the closest five minutes?

I am working with a dataframe in pandas. In this dataframe there is a column which type is datetime. It represents the moment in which a product is sold, other columns indicate the price, the type, amount sold, amount remaining…

To do an analysis, I want more datetime columns to check how many products are sold in intervals from 5 minutes to one hour. I need to convert the datetime data to the upper five minutes.

As an example for the 5 minutes case:

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

2023-11-16 13:17:32 would become 2023-11-16 13:20:00, 2023-11-16 13:21:09 would become 2023-11-16 13:25:00 and so on.

For the 1 hour case, both of them would become 2023-11-16 14:00:00.

Can this be done?

I know the functions ceil and floor, but I don’t know how to use them in datetime format

>Solution :

A possible solution, which uses pandas.Series.dt.ceil:

df = pd.DataFrame({
    'col': pd.to_datetime([
        '2023-11-16 13:17:32',
        '2023-11-16 13:21:09',
    ])
})

df['rounded_5m'] = df['col'].dt.ceil('5T')
df['rounded_1h'] = df['col'].dt.ceil('1H')

Output:

                  col          rounded_5m          rounded_1h
0 2023-11-16 13:17:32 2023-11-16 13:20:00 2023-11-16 14:00:00
1 2023-11-16 13:21:09 2023-11-16 13:25:00 2023-11-16 14:00:00
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