1

I have string column in polars dataframe with multiple datetime formats and I am using following code to convert datatype of column from string into datetime.

import polars as pl

df = pl.from_dict({'a': ["2025-11-17 11:51:44 UTC", "17.11.2025 11:51:44 UTC"]})

expr = (
    pl.when(pl.col("a").str.starts_with("2025"))
    .then(pl.col("a").str.to_datetime("%F %T %Z"))
    .otherwise(pl.col("a").str.to_datetime("%d.%m.%Y %T %Z"))
    .alias("a")
)

df.with_columns(expr)

However I am getting following error.


InvalidOperationError: conversion from `str` to `datetime[μs]` failed in column 'a' for 1 out of 2 values: ["17.11.2025 11:51:44 UTC"]

You might want to try:
- setting `strict=False` to set values that cannot be converted to `null`
- using `str.strptime`, `str.to_date`, or `str.to_datetime` and providing a format string

Is there anything missing I am here? Is is okay to pass expression with then and otherwise?

1
  • 3
    when/then/otherwise executes all the expressions first, and the results are then masked. You could use non-strict parsing for each format with coalesce: stackoverflow.com/questions/76010212 Commented Nov 26 at 12:38

1 Answer 1

0
import polars as pl

df = pl.from_dict({
    "a": ["2025-11-17 11:51:44 UTC", "17.11.2025 11:51:44 UTC"]
})

result = df.with_columns([
    pl.when(pl.col("a").str.starts_with("2025"))
    .then(
        pl.col("a").str.strptime(pl.Datetime, "%Y-%m-%d %H:%M:%S %Z", strict=False)
    )
    .otherwise(
        pl.col("a").str.strptime(pl.Datetime, "%d.%m.%Y %H:%M:%S %Z", strict=False)
    )
    .alias("a")
])

print(result)

you can use this

Why this works

  • strict=False prevents errors and sets invalid conversions to null.

  • But because each branch selects correct rows, you will not get nulls in practice.

  • str.strptime is evaluated only on the matched rows → no cross-format parsing.

New contributor
sanya arora is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

1 Comment

The "Why this works" explanation is not true. strptime is evaluated on all rows in both cases.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.