Pandas - All day up to 30 minutes

I have built 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 am wondering if it is possible to round off the time in a 30 minute span by concluding:

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.

+3


source to share


1 answer


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

      



This works well for timedeltas:

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

      

+5


source







All Articles