pythondurationtimedeltapython-polars

How do I make a time delta column in Polars from two datetime columns


How would I make a column with the delta (in days) of two date columns. I thought I could just subtract the date objects, but I'm obviously missing something

(pl.from_records([{'start': '2021-01-01', 'end': '2022-01-01'}])
 .with_columns(pl.col(['start', 'end']).str.to_date('%Y-%m-%d'))
 .with_columns(delta = pl.col('end') - pl.col('start'))
)

Solution

  • You can try using the Expr.sub() function instead of the - operator:

     (pl.from_records([{'start': '2021-01-01', 'end': '2022-01-01'}])
     .with_columns(pl.col(['start', 'end']).str.to_date('%Y-%m-%d'))
     .with_columns(delta = pl.col('end').sub(pl.col('start'))))