Round A Pandas Timestamp Using An Offset
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.fre
Solution 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')
Solution 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
Post a Comment for "Round A Pandas Timestamp Using An Offset"