Home > Mobile >  Rounding milliseconds in Pandas datettime column
Rounding milliseconds in Pandas datettime column

Time:08-18

I have a pandas dataframe in which one column has datetime data. The format of the timestamps is like

2020-05-05 12:15:33.500000

I want to format/ round the milliseconds to the first decimal point. I am using the following code to format.

df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S:%f')  

Is there any modification I can do to round the milliseconds? Thank you in advance.

CodePudding user response:

You can't directly. You can however post process it with slicing:

df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S:%f').str[:-5]

CodePudding user response:

Slight modification of @mozway's answer:

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2022, 8, 18, 10, 42, 37, 714473)
>>> dt.strftime('%Y-%m-%d %H:%M:%S:%f')[:-5]
'2022-08-18 10:42:37:7'
  • Related