Derive calendar-year features
Create a separate year column from a date or timestamp field.
Polars · Module
Extracts the calendar year from Date or Datetime values. The expression returns Int32 output and can be composed with other Polars expressions.
Call .dt.year() on a Polars date-time expression to extract the calendar year from each value. It accepts Date and Datetime columns and produces an Int32 expression, which can be used in selections, filters, derived columns, or grouping expressions.
Expr.dt.year()Expr of data type Int32
import polars as pl
from datetime import date
df = pl.DataFrame({"date": [date(2001, 1, 1), date(2002, 1, 1)]})
result = df.with_columns(
pl.col("date").dt.year().alias("year")
)
print(result)Adds a calendar-year column extracted from the Date column.
Create a separate year column from a date or timestamp field.
Keep or exclude records based on their calendar year.
Build year-based aggregations or grouping keys.
Expr.dt.year() return, and which input types does it support?Expr.dt.year() extracts the year from the underlying Date representation and applies to Date and Datetime columns. The resulting expression has data type Int32.
Follow-up: How would you obtain the ISO week-based year instead? Use the related Expr.dt.iso_year() expression.
Expr.dt.year() typically used in a DataFrame transformation?Use it as part of an expression, such as pl.col("date").dt.year(), then alias or otherwise compose that expression. For example, with_columns can materialize the extracted year as a new column.
Follow-up: How could the extracted value be used for filtering? Compose it with a comparison, such as pl.col("date").dt.year() < 1990.
dt.year() and dt.iso_year()?The result is the calendar year represented by each date, not the ISO week-based year. Its output expression is typed as Int32.
Follow-up: Why might calendar and ISO years differ near New Year? ISO week dates can assign boundary days to the adjacent week-based year; use dt.iso_year() when that convention is required.
Expr.dt.iso_yearExpr.dt.monthExpr.dt.quarterExpr.dt.day