polars.internals.expr.ExprDateTimeNameSpace.truncate

ExprDateTimeNameSpace.truncate(every: Union[str, datetime.timedelta], offset: Optional[Union[str, datetime.timedelta]] = None) polars.internals.expr.Expr

Divide the date/ datetime range into buckets. Data must be sorted, if not the output does not make sense.

The every and offset arguments are created with the following string language:

1ns # 1 nanosecond 1us # 1 microsecond 1ms # 1 millisecond 1s # 1 second 1m # 1 minute 1h # 1 hour 1d # 1 day 1w # 1 week 1mo # 1 calendar month 1y # 1 calendar year

3d12h4m25s # 3 days, 12 hours, 4 minutes, and 25 seconds

Parameters
every

Every interval start and period length

offset

Offset the window

Returns
Date/Datetime series

Examples

>>> from datetime import timedelta, datetime
>>> start = datetime(2001, 1, 1)
>>> stop = datetime(2001, 1, 2)
>>> s = pl.date_range(start, stop, timedelta(minutes=30), name="dates")
>>> s
shape: (49,)
Series: 'dates' [datetime[ns]]
[
    2001-01-01 00:00:00
    2001-01-01 00:30:00
    2001-01-01 01:00:00
    2001-01-01 01:30:00
    2001-01-01 02:00:00
    2001-01-01 02:30:00
    2001-01-01 03:00:00
    2001-01-01 03:30:00
    2001-01-01 04:00:00
    2001-01-01 04:30:00
    2001-01-01 05:00:00
    2001-01-01 05:30:00
    ...
    2001-01-01 18:30:00
    2001-01-01 19:00:00
    2001-01-01 19:30:00
    2001-01-01 20:00:00
    2001-01-01 20:30:00
    2001-01-01 21:00:00
    2001-01-01 21:30:00
    2001-01-01 22:00:00
    2001-01-01 22:30:00
    2001-01-01 23:00:00
    2001-01-01 23:30:00
    2001-01-02 00:00:00
]
>>> s.dt.truncate("1h")
shape: (49,)
Series: 'dates' [datetime[ns]]
[
    2001-01-01 00:00:00
    2001-01-01 00:00:00
    2001-01-01 01:00:00
    2001-01-01 01:00:00
    2001-01-01 02:00:00
    2001-01-01 02:00:00
    2001-01-01 03:00:00
    2001-01-01 03:00:00
    2001-01-01 04:00:00
    2001-01-01 04:00:00
    2001-01-01 05:00:00
    2001-01-01 05:00:00
    ...
    2001-01-01 18:00:00
    2001-01-01 19:00:00
    2001-01-01 19:00:00
    2001-01-01 20:00:00
    2001-01-01 20:00:00
    2001-01-01 21:00:00
    2001-01-01 21:00:00
    2001-01-01 22:00:00
    2001-01-01 22:00:00
    2001-01-01 23:00:00
    2001-01-01 23:00:00
    2001-01-02 00:00:00
]
>>> assert s.dt.truncate("1h") == s.dt.truncate(timedelta(hours=1))