Rounding Pandas Timestamps to the Nearest Minute, 15M, 30M
Below you can find multiple ways to round to the nearest minute or seconds in Pandas:
(1) rounding pandas timestamp
pd.to_datetime(df['date']).dt.round(freq='30min').dt.time
result:
0 11:00:00
1 12:30:00
2 12:00:00
3 15:30:00
Name: date, dtype: object
(2) round date to 30 minutes python
df['date'].dt.round('15min')
results:
0 2024-09-01 11:00:00
1 2024-09-01 12:30:00
2 2024-09-01 12:15:00
3 2024-09-01 15:45:00
Name: date, dtype: datetime64[ns]
(3) rounding pandas timestamps to the nearest minute or 5 minutes
df['date'].dt.round('5min')
0 2024-09-01 11:05:00
1 2024-09-01 12:35:00
2 2024-09-01 12:15:00
3 2024-09-01 16:00:00
Name: date, dtype: datetime64[ns]
(4) round to a minute in python/pandas
df['date'].dt.round("10s")
result:
0 2024-09-01 11:04:40
1 2024-09-01 12:35:20
2 2024-09-01 12:16:30
3 2024-09-01 15:58:00
Name: date, dtype: datetime64[ns]
(4) floor to a closest minute
df['date'].dt.floor('30min')
result:
0 2024-09-01 11:00:00
1 2024-09-01 12:30:00
2 2024-09-01 12:00:00
3 2024-09-01 15:30:00
Name: date, dtype: datetime64[ns]
(5) ceil to a closest minute
df['date'].dt.ceil('30min')
result:
0 2024-09-01 11:30:00
1 2024-09-01 13:00:00
2 2024-09-01 12:30:00
3 2024-09-01 16:00:00
Name: date, dtype: datetime64[ns]
Different frequencies to round
d
- dayh
- hourmin
- minutes
- second
Sample Data
import pandas as pd
data = {
'date': [
pd.Timestamp('2024-09-01 11:04:45'),
pd.Timestamp('2024-09-01 12:035:15'),
pd.Timestamp('2024-09-01 12:16:30'),
pd.Timestamp('2024-09-01 15:57:59')
]
}
df = pd.DataFrame(data)
df