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.
You can use round(freq) . There is also a shortcut column. dt for datetime functions access (as @laurens-koppenol suggests). Save this answer.
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") .
The round() function in pandas is used to round up a DataFrame to a specified number of decimal places.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With