Round a Pandas Timestamp using an offset

2019-08-18 04:17发布

问题:

I would like to round (floor) a Pandas Timestamp using a pandas.tseries.offsets (like when resampling time series but with just one row)

import pandas as pd
from pandas.tseries.frequencies import to_offset
freq = to_offset("H")
dt = pd.Timestamp('2017-01-03 05:02:00')
# what should I do
# to get pd.Timestamp('2017-01-03 05:00:00')

I wonder if pandas.core.resample.TimeGrouper can't help

grouper = pd.Grouper(freq="H")

回答1:

Timestamps may be rounded down using a time frequency string:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.floor.html

pd.Timestamp.now().floor('M')
pd.Timestamp.now().floor('H')
pd.Timestamp.now().floor('D')


回答2:

There may be a way to do it with offsets, but if you're just trying to "floor" timestamps to the format '%H:00:00', you could also just use the replace method that pd.Timestamps inherit from datetime.datetime (see this answer)

dt = pd.Timestamp('2017-01-03 05:02:00')

dt.replace(minute=0, second=0)

# Timestamp('2017-01-03 05:00:00')

If you wanted to do this on a whole column of datetimes, you could just apply it as a lambda:

df = pd.DataFrame(pd.date_range('2018-01-01 09:00:00','2018-01-01 10:00:00', freq='S'), columns = ['datetime'])

>>> df.head()
             datetime
0 2018-01-01 09:00:00
1 2018-01-01 09:00:01
2 2018-01-01 09:00:02
3 2018-01-01 09:00:03
4 2018-01-01 09:00:04

df['datetime'] = df.datetime.apply(lambda x: x.replace(minute=0, second=0))

>>> df.head()
0   2018-01-01 09:00:00
1   2018-01-01 09:00:00
2   2018-01-01 09:00:00
3   2018-01-01 09:00:00
4   2018-01-01 09:00:00