Sub topic 12
String and datetime namespaces
This chapter maps the pandas .str and .dt accessors to their Polars equivalents. It assumes you know the Polars expression model from earlier chapters (pl.col, with_columns, select) and can read pandas string and datetime code.
How the namespaces work
In pandas, .str and .dt are accessors on a Series. Polars has the same idea, but the accessors are namespaces on an expression. pl.col("name").str.to_uppercase() is still an expression, so it works in select, with_columns, filter and agg, and it works on a LazyFrame.
Two rules hold in both libraries. .str needs a string column and .dt needs a date or datetime column. Polars checks this against the schema, so a call on the wrong dtype raises an error instead of returning NaN.
String operations
Most pandas methods have a direct counterpart. The names differ in a few places.
| pandas | Polars | Note |
|---|---|---|
| `s.str.lower()` | `str.to_lowercase()` | Also `to_uppercase()` |
| `s.str.strip()` | `str.strip_chars()` | Takes a set of characters to strip |
| `s.str.contains(p)` | `str.contains(p)` | Both treat `p` as a regex by default |
| `s.str.replace(p, r)` | `str.replace(p, r)` | Replaces only the first match |
| `s.str.replace(p, r, regex=False)` | `str.replace_all(p, r, literal=True)` | Replaces every match |
| `s.str.len()` | `str.len_chars()` | `len_bytes()` counts bytes |
| `s.str.split("@").str[1]` | `str.split("@").list.get(1)` | `split` returns a List column |
| `s.str.extract(p)` | `str.extract(p, 1)` | The second argument is the capture group index |
import polars as pl
df = pl.DataFrame(
{
"email": [" [email protected] ", "[email protected]", None],
"code": ["A-100", "B-20", "C-3"],
}
)
cleaned = df.with_columns(
pl.col("email").str.strip_chars().str.to_lowercase().alias("email_clean")
).with_columns(
pl.col("email_clean").str.split("@").list.get(1).alias("domain"),
pl.col("email_clean").str.contains("example", literal=True).alias("is_example"),
pl.col("code").str.extract(r"(\d+)", 1).cast(pl.Int64).alias("number"),
)
print(cleaned)The example makes two points. First, a null input gives a null output. contains on a null email returns null, not False, so filter(pl.col("email_clean").str.contains(...)) drops those rows. Use .fill_null(False) if you want them treated as non-matches. Second, extract returns a string, so you must cast the result before doing arithmetic on it.
String gotchas when porting
- pandas
str.replacereplaced all matches. Polarsreplacereplaces only the first. Port every pandasstr.replacetoreplace_allunless you checked that one match is enough. - Regex syntax comes from the Rust
regexcrate. It does not support look-around or backreferences. Patterns that rely on them need rewriting, or useliteral=Truewhen you only need plain text. - Polars has no
str.get_dummiesequivalent in the string namespace. Usedf.to_dummies()on the column instead. - For case-insensitive matching, put
(?i)at the start of the pattern.
Parsing strings into datetimes
pandas often parses dates with pd.to_datetime or parse_dates= in read_csv. Polars does the same work with str.to_datetime, str.to_date or str.strptime. Give an explicit format whenever you know it. It is faster, and it avoids silently guessing a different layout than you intended.
import polars as pl
df = pl.DataFrame(
{
"ts": ["2026-01-15 08:30:00", "2026-02-03 17:45:00", "2026-02-20 09:10:00"],
"amount": [10, 20, 30],
}
)
df = df.with_columns(pl.col("ts").str.to_datetime("%Y-%m-%d %H:%M:%S"))
print(df.schema) # ts is now DatetimeWhen reading files, pl.read_csv("file.csv", try_parse_dates=True) is the closest match to parse_dates. It only detects common ISO-style layouts. For anything else, read the column as a string and parse it yourself.
By default, a value that does not match the format raises an error. Pass strict=False to turn bad values into nulls instead, which matches errors="coerce" in pandas. Count the new nulls afterwards so you notice parse failures.
Datetime parts and arithmetic
The dt namespace gives you parts, truncation and formatting.
import polars as pl
df = pl.DataFrame(
{
"ts": ["2026-01-15 08:30:00", "2026-02-03 17:45:00", "2026-02-20 09:10:00"],
"amount": [10, 20, 30],
}
).with_columns(pl.col("ts").str.to_datetime("%Y-%m-%d %H:%M:%S"))
parts = df.with_columns(
pl.col("ts").dt.year().alias("year"),
pl.col("ts").dt.month().alias("month"),
pl.col("ts").dt.weekday().alias("weekday"),
pl.col("ts").dt.truncate("1mo").alias("month_start"),
pl.col("ts").dt.strftime("%b %d").alias("label"),
(pl.col("ts") - pl.col("ts").min()).dt.total_days().alias("days_since_first"),
)
print(parts)Points to watch:
dt.weekday()is ISO-based, with Monday as 1 and Sunday as 7. pandasdt.dayofweekuses Monday as 0. Any code that compares against 5 or 6 for the weekend needs adjusting.- Subtracting two datetimes gives a
Durationcolumn. Usedt.total_days(),dt.total_hours()and similar methods. They replace pandasdt.days, which returned only the day component. dt.truncate("1mo")plays the role ofdt.to_period("M")ordt.floor. The result is still a Datetime, not a Period. Polars has no Period dtype.dt.offset_by("1mo")adds calendar-aware offsets, likepd.DateOffset.
Resampling
The pandas resample method becomes either truncate plus group_by, or group_by_dynamic.
import polars as pl
df = pl.DataFrame(
{
"ts": ["2026-01-15 08:30:00", "2026-02-03 17:45:00", "2026-02-20 09:10:00"],
"amount": [10, 20, 30],
}
).with_columns(pl.col("ts").str.to_datetime("%Y-%m-%d %H:%M:%S"))
monthly = (
df.sort("ts")
.group_by_dynamic("ts", every="1mo")
.agg(pl.col("amount").sum().alias("total"))
)
print(monthly)group_by_dynamic requires the time column to be sorted, and it raises an error or gives wrong windows if it is not. Sort first, as above. The truncate approach does not need sorting, but it only returns months that have data. group_by_dynamic also emits only windows that contain rows, so fill gaps afterwards if you need empty periods.
Time zones
Polars datetimes are naive until you attach a zone. Use dt.replace_time_zone("UTC") to label naive values with a zone, and dt.convert_time_zone("Europe/Berlin") to change the zone of values that already have one. Mixing these up is the most common bug: replace changes the label and keeps the wall-clock time, while convert keeps the instant. This is the same distinction as tz_localize and tz_convert in pandas.
Exercise
A pandas script runs df["name"].str.replace("-", " ", regex=False) and df["when"].dt.dayofweek >= 5 to find weekends. Write the Polars expressions, and say what must change in each.
Show answer
Use pl.col("name").str.replace_all("-", " ", literal=True), because Polars replace changes only the first match while the pandas call changed all of them. For weekends use pl.col("when").dt.weekday() >= 6, because Polars weekdays run from Monday=1 to Sunday=7, so Saturday and Sunday are 6 and 7.