pandasdatetimetime

How to get rid of milliseconds for datetime in Python


I have my DateTime like this

0       2021-02-01 00:01:02.327
1       2021-02-01 00:01:21.445
2       2021-02-01 00:01:31.912
3       2021-02-01 00:01:32.600
4       2021-02-01 00:02:08.920

However, I would like them in the format of %Y.%m.%d %H:%M:%S. I have tried with these methods, but they did not make any difference.

df['Date'] = pd.to_datetime(df['Date']).dt.time

or

df['Date'] = pd.to_datetime(df['Date'],format='%Y.%m.%d %H:%M:%S')

Another quick question is if I would like to add a new column named 'Time', could I please have them only have the information only in %H:%M:%S from Date column?

0       00:01:02.327
1       00:01:21.445
2       00:01:31.912
3       00:01:32.600
4       00:02:08.920

Solution

  • Use Series.dt.floor by seconds:

    df['Date'] = pd.to_datetime(df['Date']).dt.floor('S')