Home > Software engineering >  Rounding datetime to the nearest second instead returns date rounded to day
Rounding datetime to the nearest second instead returns date rounded to day

Time:11-02

When I round my datetime's to the nearest second, it rounds it to the nearest day instead.

I have data with the following timestamps:

    timestamp
1   2018-06-01 23:59:59.894110
2   2018-06-01 23:59:59.894110
3   2018-06-01 23:59:59.894110
4   2018-06-01 23:59:59.894110
5   2018-06-01 23:59:59.894110

I want to round them to the nearest second to get rid of milliseconds. So first I convert to datetime object: df['timestamp'] = pd.to_datetime(df['timestamp'], format = '%Y-%m-%d %H:%M:%S.%f')

And now to round, I run: df['timestamp'] = df.timestamp.dt.round('1s')

And this is what it returns:

1   2018-06-01
2   2018-06-01
3   2018-06-01
4   2018-06-01
5   2018-06-01

For some reason, it drops the HH:MM:SS part. What am I doing wrong?

CodePudding user response:

For some reason, it drops the HH:MM:SS part. What am I doing wrong?

It is not removed, only not displayed, because HH:MM:SS is 00:00:00 for all data which are printed.

You can check it:

print (df['timestamp'].tolist())
  • Related