pythondatetimepython-polars

How to get the day / month name of a column in polars


I have a polars dataframe df which has a datetime column date. I'm trying to get the name of the day and month of that column.

Consider the following example.

import polars as pl
from datetime import datetime

df = pl.DataFrame({
    "date": [datetime(2024, 10, 1), datetime(2024, 11, 2)]
})

I was hoping that I could pass parameter to month() or weekday() to get the desired format.

df.with_columns(
    pl.col("date").dt.month().alias("Month"),
    pl.col("date").dt.weekday().alias("Day")
)
shape: (2, 3)
┌─────────────────────┬───────┬─────┐
│ date                ┆ Month ┆ Day │
│ ---                 ┆ ---   ┆ --- │
│ datetime[μs]        ┆ i8    ┆ i8  │
╞═════════════════════╪═══════╪═════╡
│ 2024-10-01 00:00:00 ┆ 10    ┆ 2   │
│ 2024-11-02 00:00:00 ┆ 11    ┆ 6   │
└─────────────────────┴───────┴─────┘

However, this does not seem to be the case. My desired output looks as follows.

shape: (2, 3)
┌─────────────────────┬───────┬──────────┐
│ date                ┆ Month ┆ Day      │
│ ---                 ┆ ---   ┆ ---      │
│ datetime[μs]        ┆ str   ┆ str      │
╞═════════════════════╪═══════╪══════════╡
│ 2024-10-01 00:00:00 ┆ Oct   ┆ Tuesday  │
│ 2024-11-02 00:00:00 ┆ Nov   ┆ Saturday │
└─────────────────────┴───────┴──────────┘

How can I extract the day and month name from the date column?


Solution

  • You can use pl.Expr.dt.strftime to convert a date / time / datetime column into a string column of a given format.

    The format can be specified using the chrono strftime format. In your specific example, the following specifiers might be of interest:

    df.with_columns(
        pl.col("date").dt.strftime("%B").alias("month"),
        pl.col("date").dt.strftime("%b").alias("month (short)"),
        pl.col("date").dt.strftime("%A").alias("day"),
        pl.col("date").dt.strftime("%a").alias("day (short)"),
    )
    
    shape: (2, 5)
    ┌─────────────────────┬──────────┬───────────────┬──────────┬─────────────┐
    │ date                ┆ month    ┆ month (short) ┆ day      ┆ day (short) │
    │ ---                 ┆ ---      ┆ ---           ┆ ---      ┆ ---         │
    │ datetime[μs]        ┆ str      ┆ str           ┆ str      ┆ str         │
    ╞═════════════════════╪══════════╪═══════════════╪══════════╪═════════════╡
    │ 2024-10-01 00:00:00 ┆ October  ┆ Oct           ┆ Tuesday  ┆ Tue         │
    │ 2024-11-02 00:00:00 ┆ November ┆ Nov           ┆ Saturday ┆ Sat         │
    └─────────────────────┴──────────┴───────────────┴──────────┴─────────────┘