zipa
zipa

Reputation: 27869

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.

Upvotes: 7

Views: 4009

Answers (1)

jezrael
jezrael

Reputation: 862661

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

Upvotes: 10

Related Questions