Sub topic 8
String and datetime expressions
This chapter assumes you know how select and with_columns work and how pl.col builds an expression. Here you will use two groups of expression methods. They are called namespaces, and they are .str and .dt.
What a namespace is
A namespace is a group of methods attached to an expression, and you reach it through an attribute. pl.col("name").str.to_lowercase() is still an expression. It runs inside a context like any other, and it works on the whole column at once.
The namespace must match the column's data type. .str needs a String column and .dt needs a Date, Datetime or Duration column. Calling the wrong one raises an error. A column of dates stored as text is a String, so you must parse it before .dt methods work.
Cleaning and extracting strings
import polars as pl
df = pl.DataFrame(
{
"name": [" Ana Lopez ", "ben ng", "CY Roe"],
"email": ["[email protected]", "[email protected]", "[email protected]"],
"signup": [
"2026-01-15 09:30:00",
"2026-02-03 17:45:00",
"2026-02-28 08:00:00",
],
}
)
cleaned = df.with_columns(
pl.col("name").str.strip_chars().str.to_titlecase().alias("name_clean"),
pl.col("email").str.extract(r"@(.+)$", 1).alias("domain"),
pl.col("email").str.contains(r"\.com$").alias("is_com"),
)
print(cleaned.select("name_clean", "domain", "is_com"))String methods chain, so strip_chars() feeds to_titlecase(). str.contains returns a boolean column, so you can pass it straight to filter. str.extract takes a regular expression and a capture group number, and it returns null where nothing matches.
| Method | Result |
|---|---|
| `str.strip_chars()` | Removes surrounding whitespace |
| `str.replace_all(a, b)` | Replaces every match |
| `str.starts_with(s)` | Boolean column |
| `str.len_chars()` | Length in characters |
| `str.split(sep)` | A list column |
Parsing text into datetimes
str.to_datetime takes a format string and returns a Datetime column.
parsed = df.with_columns(
pl.col("signup").str.to_datetime("%Y-%m-%d %H:%M:%S").alias("signup_dt")
)
print(parsed.schema)The schema now shows signup_dt as Datetime. By default a value that does not match the format raises an error. Pass strict=False if you want such values to become null instead. Then check for new nulls afterwards, so bad rows do not disappear without notice.
Extracting parts and doing date arithmetic
from datetime import datetime
report = parsed.with_columns(
pl.col("signup_dt").dt.year().alias("year"),
pl.col("signup_dt").dt.month().alias("month"),
pl.col("signup_dt").dt.truncate("1mo").alias("month_start"),
pl.col("signup_dt").dt.strftime("%b %d").alias("label"),
(pl.lit(datetime(2026, 3, 1)) - pl.col("signup_dt"))
.dt.total_days()
.alias("days_before_march"),
)
print(report.select("year", "month", "month_start", "label", "days_before_march"))Subtracting two datetimes gives a Duration, and dt.total_days() turns it into a whole number of days. dt.truncate("1mo") rounds each timestamp down to the start of its month. It is a convenient grouping key:
print(
parsed.group_by(pl.col("signup_dt").dt.truncate("1mo").alias("month"))
.agg(pl.len().alias("signups"))
.sort("month")
)Common errors
- Calling
.stron a column that is alreadyDatetime, or.dton aString. Checkdf.schemafirst. - Using a format string that does not match the text exactly, such as
%dfor a day written without zero padding. - Forgetting that string methods return new values.
str.strip_chars()on its own changes nothing until you put it in a context.
Exercise
A column ts holds text such as "2026-05-17". Write an expression that gives the year as an integer.
Show answer
pl.col("ts").str.todate("%Y-%m-%d").dt.year() parses the text into a Date, then extracts the year. Use it inside select or withcolumns.
Exercise
Why might pl.col("signup").dt.year() fail on the DataFrame df from this chapter?
Show answer
signup is a String column in df, so the .dt namespace is not available. Parse it first with str.to_datetime.