[Python] Polars parse multiple datetime format [duplicate]

Discussão em 'Python' iniciado por Stack, Novembro 26, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página