Search code examples
pythondatetimepython-polars

Add X days to a Datetime Series


I have a Datetime Series that always contains the datetime of yesterday like:

Series: '' [datetime[ns]]
[
    2024-08-29 00:00:00
]

How can I add 2 days to that Datetime Series so that I can add the datetime from 2 days and 3 days ago?

End result should be:

Series: '' [datetime[ns]]
[
    2024-08-29 00:00:00
    2024-08-28 00:00:00
    2024-08-27 00:00:00
]

Solution

  • pl.date_range can be used along with pl.Series.dt.offset_by to create the start date.

    pl.date_range(dates.dt.offset_by("-2d"), dates, eager=True)
    
    shape: (3,)
    Series: 'dates' [date]
    [
        2024-08-27
        2024-08-28
        2024-08-29
    ]
    

    If the series is required in decreasing order, one can subsequently reverse the series using pl.Series.reverse.

    pl.date_range(dates.dt.offset_by("-2d"), dates, eager=True).reverse()