2

I am trying to convert a str column in the DataFrame into Date format of YYYY-MM-DD. How to convert different date format into one format of YYYY-MM-DD?

import polars as pl

s = pl.Series("date",["Sun Jul  8 00:34:60 2001", "12Mar2022", "12/Mar/2022"])

df = s.to_frame().with_columns(pl.col("date").str.to_date("%d%m%Y", strict=False)) 
shape: (3, 1)
┌──────┐
│ date │
│ ---  │
│ date │
╞══════╡
│ null │
│ null │
│ null │
└──────┘

1 Answer 1

6

If you have multiple known formats you can use pl.coalesce to combine the results of each parse attempt into a single column.

df = pl.from_repr("""
┌──────────────────────────┐
│ date                     │
│ ---                      │
│ str                      │
╞══════════════════════════╡
│ Sun Jul  8 00:34:60 2001 │
│ 12Mar2022                │
│ 12/Mar/2022              │
└──────────────────────────┘
""")

fmts = "%d/%b/%Y", "%d%b%Y", "%c"

df.with_columns(
   pl.coalesce(
      pl.col("date").str.to_datetime(fmt, strict=False)
      for fmt in fmts
   )
)
shape: (3, 1)
┌─────────────────────┐
│ date                │
│ ---                 │
│ datetime[μs]        │
╞═════════════════════╡
│ 2001-07-08 00:35:00 │
│ 2022-03-12 00:00:00 │
│ 2022-03-12 00:00:00 │
└─────────────────────┘
Sign up to request clarification or add additional context in comments.

3 Comments

it doesn't worked inside pl.scan_csv().withcolumns()
@Samboo How is it not working? Can you give a code example?
In Polars documentation, you will be able to find a use case: docs.pola.rs/api/python/dev/reference/expressions/api/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.