I have a dataframe with thousands of rows, there is a column which is datetime:
I would like to adjust the time, a little like 00 ± 15 -> 00, and 30±15 ->30. More precise saying is the minute within the range 46<->15 will change to 00, 16<->45 will change to 30, but it also needs care ± 1 on the hour
datetime
2022/11/15 00:29
2022/11/15 00:29
2022/11/15 00:29
2022/11/15 00:59
2022/11/15 00:59
2022/11/15 00:59
2022/11/15 01:35
2022/11/15 01:35
2022/11/15 01:35
2022/11/15 02:01
2022/11/15 02:01
2022/11/15 02:01
2022/11/15 02:45
2022/11/15 02:45
2022/11/15 02:45
2022/11/15 02:48
2022/11/15 02:48
2022/11/15 02:48
After adjustment, it would become
datetime
2022/11/15 00:30
2022/11/15 00:30
2022/11/15 00:30
2022/11/15 01:00
2022/11/15 01:00
2022/11/15 01:00
2022/11/15 01:30
2022/11/15 01:30
2022/11/15 01:30
2022/11/15 02:00
2022/11/15 02:00
2022/11/15 02:00
2022/11/15 02:30
2022/11/15 02:30
2022/11/15 02:30
2022/11/15 03:00
2022/11/15 03:00
2022/11/15 03:00
CodePudding user response:
Use Series.dt.ceil
by 15 minutes and then Series.dt.floor
by 30:
df['datetime'] = pd.to_datetime(df['datetime']).dt.ceil('15Min').dt.floor('30Min')
print (df)
datetime
0 2022-11-15 00:30:00
1 2022-11-15 00:30:00
2 2022-11-15 00:30:00
3 2022-11-15 01:00:00
4 2022-11-15 01:00:00
5 2022-11-15 01:00:00
6 2022-11-15 01:30:00
7 2022-11-15 01:30:00
8 2022-11-15 01:30:00
9 2022-11-15 02:00:00
10 2022-11-15 02:00:00
11 2022-11-15 02:00:00
12 2022-11-15 02:30:00
13 2022-11-15 02:30:00
14 2022-11-15 02:30:00
15 2022-11-15 03:00:00
16 2022-11-15 03:00:00
17 2022-11-15 03:00:00