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-0109:00:00','2018-01-0110:00:00',freq='S'),columns= ['datetime'])>>>df.head()datetime02018-01-01 09:00:0012018-01-01 09:00:0122018-01-01 09:00:0232018-01-01 09:00:0342018-01-01 09:00:04df['datetime']=df.datetime.apply(lambdax:x.replace(minute=0,second=0))>>>df.head()02018-01-01 09:00:0012018-01-01 09:00:0022018-01-01 09:00:0032018-01-01 09:00:0042018-01-01 09:00:00
Post a Comment for "Round A Pandas Timestamp Using An Offset"