Search code examples
pythonpython-polars

Create date_range with predefined number of periods in polars


When I create a date range in pandas, I often use the periods argument. Something like this:

pd.date_range(start='1/1/2018', periods=8)
DatetimeIndex(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04',
               '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'],
              dtype='datetime64[ns]', freq='D')

What would be the equivalent way in polars? I am missing the periods input parameter in pl.date_range.

Having said that, there's probably an easy and clever solution ;-)


Solution

  • Adding a periods argument has been an open feature request for a while now.

    Until the request has been implemented, you can make start an expression and create end by offsetting start by the desired number of periods (using pl.Expr.dt.offset_by).

    start = pl.lit("1/1/2018").str.to_date()
    pl.date_range(start=start, end=start.dt.offset_by("7d"), eager=True)
    
    shape: (8,)
    Series: 'literal' [date]
    [
        2018-01-01
        2018-01-02
        2018-01-03
        2018-01-04
        2018-01-05
        2018-01-06
        2018-01-07
        2018-01-08
    ]