Datetime (experimental)
floor_date(), ceil_date()
from siuba.experimental.datetime import floor_date, ceil_date
floor_date(x, unit='S')
floor_date and ceil_date return dates rounded to nearest specified unit.
These functions address limitations in pandas' round() method, which cannot round down to, e.g., the month.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
a DatetimeIndex, PeriodIndex, or their underlying arrays or elements. |
required | |
units |
a date or time unit for rounding (eg. "MS" rounds down or up to the start of a month) |
required |
Examples:
>>> import pandas as pd
>>> a_date = "2020-02-02 02:02:02"
>>> dti = pd.DatetimeIndex([a_date])
>>> dti.floor("MS")
Traceback (most recent call last):
...
ValueError: <MonthBegin> is a non-fixed frequency
Month start will always go to the first day of a month.
>>> floor_date(dti, "MS")
DatetimeIndex(['2020-02-01'], dtype='datetime64[ns]', freq=None)
>>> ceil_date(dti, "MS")
DatetimeIndex(['2020-03-01'], dtype='datetime64[ns]', freq=None)
On the other hand, here is month end.
>>> floor_date(dti, "M")
DatetimeIndex(['2020-01-31'], dtype='datetime64[ns]', freq=None)
>>> ceil_date(dti, "M")
DatetimeIndex(['2020-02-29'], dtype='datetime64[ns]', freq=None)
It also works on things supported by the Series.dt.floor method, like hours.
>>> floor_date(dti, "H")
DatetimeIndex(['2020-02-02 02:00:00'], dtype='datetime64[ns]', freq=None)
You can also use it on other types, like a PeriodIndex
>>> per = pd.PeriodIndex([a_date], freq = "S")
>>> floor_date(per, "M")
PeriodIndex(['2020-02'], dtype='period[M]'...
Source code in siuba/experimental/datetime.py
@symbolic_dispatch
def floor_date(x, unit = "S"):
raise TypeError("floor_date not implemented for class {}".format(type(x)))