Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Round date to 30 minutes

I have constructed this dataframe:

import pandas as pd
from pandas.compat import StringIO

temp = '''A,B
A,23:59:32.897000
B,17:36:09.182000
C,21:56:57.325000
D,06:16:24.482000'''

df = pd.read_csv(StringIO(temp))
df['B'] = pd.to_datetime(df['B']).dt.time

So I'm wondering is it possible to round down the time on 30 minutes interval making the output into:

A,B
A,23:30:00.000000
B,17:30:00.000000
C,21:30:00.000000
D,06:00:00.000000

Any help is appreciated.

like image 763
zipa Avatar asked Apr 24 '17 10:04

zipa


People also ask

How do I round datetime column to nearest quarter hour?

You can use round(freq) . There is also a shortcut column. dt for datetime functions access (as @laurens-koppenol suggests). Save this answer.

How do Pandas round dates?

In order to round a DateTime object to the nearest day, you need to use the round operation from Pandas on the DateTime column and specify the frequency that you want to use. For rounding to the nearest day you will need to use round("D") .

How do Pandas round up?

The round() function in pandas is used to round up a DataFrame to a specified number of decimal places.


1 Answers

You need dt.floor with dt.time:

df['B'] = pd.to_datetime(df['B']).dt.floor('30T').dt.time
print (df)
   A         B
0  A  23:30:00
1  B  17:30:00
2  C  21:30:00
3  D  06:00:00

It works nice for timedeltas too:

df['B'] = pd.to_timedelta(df['B']).dt.floor('30T')
print (df)
   A        B
0  A 23:30:00
1  B 17:30:00
2  C 21:30:00
3  D 06:00:00

print (df.dtypes)
A             object
B    timedelta64[ns]
dtype: object
like image 64
jezrael Avatar answered Sep 19 '22 19:09

jezrael