Sub topic 8
String and datetime expressions
Real data often arrives as text: padded email addresses, dates stored as "2024-03-01", timestamps with no time zone. Polars handles this with namespaces, which are groups of methods attached to an expression. This chapter covers the str and dt namespaces.
This chapter assumes you know pl.col, the select, with_columns and filter contexts, and group_by. It also assumes you know that missing values in Polars are null.
What a namespace is
An expression has a few methods of its own, such as alias and sum. Methods that only make sense for one data type live in a namespace on the expression:
| Namespace | Works on | Example |
|---|---|---|
| `str` | `String` columns | `pl.col("email").str.to_lowercase()` |
| `dt` | `Date`, `Datetime`, `Duration` columns | `pl.col("signup").dt.year()` |
| `list` | `List` columns | `pl.col("tags").list.len()` |
Calling a namespace on the wrong dtype raises an error. For example, .dt.year() on a String column fails at execution. The fix is to convert the column to a date first. That makes the usual workflow two steps: clean the text, then parse it into a temporal type.
Cleaning and extracting strings
Every str method is an expression. It runs over the whole column and returns a new column of the same length. A null input gives a null output, so you don't need to guard against missing values.
import polars as pl
df = pl.DataFrame(
{
"email": [" [email protected]", "[email protected] ", "[email protected]", None],
"signup": ["2024-01-15", "2024-02-29", "2024-03-01", "not a date"],
}
)
clean = df.with_columns(
pl.col("email").str.strip_chars().str.to_lowercase(),
pl.col("email").str.len_chars().alias("raw_length"),
)
print(clean)strip_chars() removes whitespace from both ends. Without arguments it strips whitespace, and with an argument it strips any of the listed characters. Both expressions in this with_columns read the original email column, because expressions in one context all see the same input frame. raw_length therefore counts the padded text. The first row has a leading space, so its length is 16 instead of 15. The null row stays null in both new columns.
len_chars() counts characters, and len_bytes() counts UTF-8 bytes. They differ for text such as "é".
Searching, extracting and replacing
These methods cover most text work:
str.contains(pattern)returns a boolean column, so it works insidefilterorwhen.str.starts_with(prefix)andstr.ends_with(suffix)do plain prefix and suffix tests.str.extract(pattern, group_index)returns one capture group of the first match, or null when nothing matches.str.replace(pattern, value)replaces the first match.str.replace_allreplaces every match.str.split(by)returns aListcolumn, which you can index with.list.get(0).
parsed = clean.with_columns(
pl.col("email").str.extract(r"@(.+)$", 1).alias("domain"),
pl.col("email").str.contains("example.com", literal=True).alias("is_com"),
pl.col("email").str.replace_all(r"[aeiou]", "*").alias("masked"),
)
print(parsed.select("email", "domain", "is_com", "masked"))The pattern @(.+)$ captures everything after the @. For [email protected] the domain is example.com. The is_com column is True for rows 1 and 3, False for [email protected], and null for the missing email.
Regex rules to remember
Patterns are regular expressions by default. Polars uses the Rust regex engine, which has two practical consequences:
- Lookaheads, lookbehinds and backreferences are not supported. A pattern that uses them raises an error.
- In a replacement string,
$1or${1}inserts a capture group. To write a literal dollar sign, use$$, or passliteral=True.
Pass literal=True whenever the text is plain. A . in "example.com" otherwise matches any character, so "exampleXcom" would match too. Literal matching also skips regex compilation, so it is faster.
For case-insensitive matching without lowercasing the column, put (?i) at the start of the pattern.
Parsing text into dates and datetimes
Date text must be parsed before any dt method can use it. Use str.to_date for dates and str.to_datetime for timestamps. Both take a format string using strftime codes such as %Y, %m, %d, %H, %M and %S.
dated = df.with_columns(
pl.col("signup").str.to_date("%Y-%m-%d", strict=False)
)
print(dated.schema)
print(dated)With strict=False, a value that does not match the format becomes null. The default is strict=True, which raises an error at the first bad value. Use strict parsing when bad dates mean a broken data feed. Use strict=False when you expect some junk, and count the nulls afterward.
Here the schema shows signup as Date, and "not a date" becomes null. "2024-02-29" is valid because 2024 is a leap year.
print(
dated.select(
pl.col("signup").is_null().sum().alias("failed_parses")
)
)This prints 1. The check works because the original column had no nulls. If it already contained nulls, compare the null count before and after parsing.
Extracting parts and doing date arithmetic
Once the column has a temporal dtype, the dt namespace exposes its parts and operations.
features = dated.drop_nulls("signup").with_columns(
pl.col("signup").dt.year().alias("year"),
pl.col("signup").dt.month().alias("month"),
pl.col("signup").dt.weekday().alias("weekday"),
pl.col("signup").dt.strftime("%b %d").alias("label"),
(pl.date(2024, 3, 31) - pl.col("signup"))
.dt.total_days()
.alias("days_to_quarter_end"),
)
print(features.select("signup", "year", "month", "weekday", "label", "days_to_quarter_end"))Points to note:
dt.weekday()follows ISO numbering, where Monday is 1 and Sunday is 7.dt.month()runs from 1 to 12.- Subtracting two
Datevalues gives aDuration. Convert it withdt.total_days(),dt.total_hours()and similar methods. pl.date(2024, 3, 31)builds a constant date expression. It broadcasts against the column, which means it is treated as the same value on every row.dt.strftimeturns a temporal value back into text. The result is aString, so you can no longer do date arithmetic on it.dt.offset_by("7d")shifts each value. It accepts strings such as"1mo","2h"and"-1d".
Truncating for time buckets
dt.truncate rounds each value down to the start of a period. It is the most common way to bucket data by month or day.
monthly = (
dated.drop_nulls("signup")
.group_by(pl.col("signup").dt.truncate("1mo").alias("month"))
.agg(pl.len().alias("signups"))
.sort("month")
)
print(monthly)The result has one row for each of 2024-01-01, 2024-02-01 and 2024-03-01, with one signup each. A group_by accepts an expression as its key, so no helper column is needed. For a regular grid with empty periods included, look at group_by_dynamic. It builds on the same period strings.
Time zones
A Datetime can be naive (no zone) or aware (tied to a zone). Two methods look similar but do different things:
| Method | Effect on the stored instant | Use it when |
|---|---|---|
| `dt.replace_time_zone("UTC")` | Keeps the wall-clock reading and attaches a zone, so the instant changes. | The timestamps were recorded in that zone but have no label. |
| `dt.convert_time_zone("America/New_York")` | Keeps the instant and changes only how it is displayed. | The column is already aware and you want local time. |
events = pl.DataFrame(
{"ts": ["2024-03-01 08:30:00", "2024-03-01 17:45:00", "2024-03-02 09:10:00"]}
).with_columns(
pl.col("ts")
.str.to_datetime("%Y-%m-%d %H:%M:%S")
.dt.replace_time_zone("UTC")
.dt.convert_time_zone("America/New_York")
)
print(events.with_columns(pl.col("ts").dt.hour().alias("local_hour")))The first event was recorded at 08:30 UTC. In New York on 1 March 2024 (UTC-5), the local hour is 3.
Common errors
.dton a string column. The message mentions the dtype. Parse first, then usedt.- Format string mismatch.
"%d/%m/%Y"will not parse"2024-03-01". Withstrict=Falsethis shows up as a column of nulls. - Unescaped regex characters. A
.,(or+in a pattern has a special meaning. Escape it or useliteral=True. - Comparing text dates.
"2024-10-01" > "2024-9-01"isFalse, because strings compare character by character. Compare parsed dates instead.
Exercise
A column ts holds text like "15/03/2024 14:05". Write an expression that parses it into a Datetime and returns the weekday number (Monday = 1), turning unparseable rows into null instead of raising an error.
Show answer
pl.col("ts").str.to_datetime("%d/%m/%Y %H:%M", strict=False).dt.weekday()
Exercise
You have a Datetime column ts with no time zone, recorded in UTC. Name the two method calls needed to show local Tokyo time, and explain why their order matters.
Show answer
pl.col("ts").dt.replacetimezone("UTC").dt.converttimezone("Asia/Tokyo"). The first call labels the naive values as UTC. The second converts the instant to Tokyo time. converttimezone cannot be applied to a naive column. Swapping the order would error, and using replacetimezone("Asia/Tokyo") alone would wrongly treat the UTC readings as Tokyo wall-clock time.