-1

I have a column in dataframe named time in format 19:46:23.12 I want to extract it like 19:46:23 and if the value after decimal point is greater than 5 need to round the value before decimal point. I have tried like:

Df['time']=Df['time'].str[:8];
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • 1
    please, read the [how-to-make-good-reproducible-pandas-examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – Brown Bear Feb 28 '19 at 07:49

1 Answers1

2

Possible your dataframe has column with type is time. Convert values to datetimes, then round by Series.dt.round and last convert to times by time:

from datetime import time

df = pd.DataFrame({'time':[time(19, 46, 23, 120000), time(19, 46, 23, 500000)]})

df['time1'] = pd.to_datetime(df['time'].astype(str)).dt.round('S').dt.time
print(df)
              time     time1
0  19:46:23.120000  19:46:23
1  19:46:23.500000  19:46:24

If need strings in HH:MM:SS format:

df['time2'] = pd.to_datetime(df['time'].astype(str)).dt.round('S').dt.strftime('%H:%M:%S')
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252