Construct date column from year, month and day in Polars

Question:

Consider the following Polars dataframe:

import polars as pl
df = pl.DataFrame({'year': [2023], 'month': [2], 'day': [1]})

I want to construct a date column from year, month and day. I know this can be done by first concatenating into a string and then parsing this:

df.with_column(
    pl.concat_str([pl.col('year'), pl.col('month'), pl.col('day')], sep='-')
    .str.strptime(pl.Date).alias('date')
)

But that seems like a detour. Is it possible to construct it directly with the three inputs? Something like this (that doesn’t work):

import datetime
df.with_column(
    datetime.date(pl.col('year'), pl.col('month'), pl.col('day')).alias('date')
)
Asked By: robertdj

||

Answers:

polars has a pl.datetime and pl.date function that works the same as base datetime except that it takes expressions so you can just do

df.with_columns(pl.date(pl.col('year'), pl.col('month'), pl.col('day')).alias('date'))
Answered By: Dean MacGregor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.