i have the following Dataframe: Dataframe
print (df)
time
0 00:00:04.4052727
1 00:00:06.5798
and my goal is to round the microseconds to 2 digits and remove the other digits so there are only 2 digits.
All columns should then look like the first row:
print (df)
time
0 00:00:04.405
1 00:00:06.580
CodePudding user response:
To round the microseconds of a datetime column in a DataFrame to two digits and remove the other digits, you can use the dt.round method and specify the microsecond parameter with a value of 100. You can then use the dt.strftime method to convert the datetime values to strings in the format you want. Here's an example of how you could do that:
# Round the microseconds to 2 digits and remove the other digits
df['time'] = df['time'].dt.round('100L')
# Convert the datetime values to strings in the desired format
df['time'] = df['time'].dt.strftime('%Y-%m-%d %H:%M:%S.%f')
CodePudding user response:
You can remove last 3 digits (000
) after convert values to HH:MM:SS.fffff
format:
df['time'] = pd.to_datetime(df['time'])
df['time'] = df['time'].dt.round('100L').dt.strftime('%H:%M:%S.%f').str[:-3]
print (df)
time
0 00:00:04.400
1 00:00:06.600
Another idea is round by 1 milisecond:
df['time'] = df['time'].dt.round('1ms')
print (df)
time
0 2022-12-12 00:00:04.405
1 2022-12-12 00:00:06.580
df['time'] = df['time'].dt.round('1ms').dt.strftime('%H:%M:%S.%f').str[:-3]
print (df)
time
0 00:00:04.405
1 00:00:06.580
If need only truncate values use Series.dt.floor
:
df['time'] = df['time'].dt.floor('1ms')
print (df)
time
0 2022-12-12 00:00:04.405
1 2022-12-12 00:00:06.579
df['time'] = df['time'].dt.floor('1ms').dt.strftime('%H:%M:%S.%f').str[:-3]
print (df)
time
0 00:00:04.405
1 00:00:06.579