Home > Back-end >  Python how to round Timestamp object to the previous full hour
Python how to round Timestamp object to the previous full hour

Time:03-05

Hi have a list of timestamp objects:

Timestamp('2021-07-07 10:00:03'), Timestamp('2021-07-07 10:02:13'), Timestamp('2021-03-07 12:40:24')

And I want to round each element at the hour level, to get:

Timestamp('2021-07-07 10:00:00'), Timestamp('2021-07-07 10:00:00'), Timestamp('2021-03-07 12:00:00')

The type of each element is

Pandas Timestamp (pandas._libs.tslibs.timestamps.Timestamp)

. What is the best way to do so?

CodePudding user response:

Given

>>> df 
                 time
0 2021-07-07 10:00:03
1 2021-07-07 10:02:13
2 2021-03-07 12:40:24

Use

>>> df['time'] = df['time'].dt.floor('1h')
>>> df 
                 time
0 2021-07-07 10:00:00
1 2021-07-07 10:00:00
2 2021-03-07 12:00:00
  • Related