pythondataframedata-manipulationpython-polars

How to transform polars datetime column into a string column?


I'm trying to change a datetime column to a string column using polars library. I only want the dates on the new column:

import polars as pl

df = pl.from_repr("""
┌─────────────────────┐
│ date_time           │
│ ---                 │
│ datetime[ns]        │
╞═════════════════════╡
│ 2007-04-19 00:00:00 │
│ 2007-05-02 00:00:00 │
│ 2007-05-03 00:00:00 │
│ 2007-05-03 00:00:00 │
└─────────────────────┘
""")

The solution below is including the time, I just need the date.

df.with_columns(pl.col('date_time').cast(pl.String))
shape: (4, 1)
┌───────────────────────────────┐
│ date_time                     │
│ ---                           │
│ str                           │
╞═══════════════════════════════╡
│ 2007-04-19 00:00:00.000000000 │
│ 2007-05-02 00:00:00.000000000 │
│ 2007-05-03 00:00:00.000000000 │
│ 2007-05-03 00:00:00.000000000 │
└───────────────────────────────┘

Solution

  • You should try this:

    # Polars
    df = df.with_columns(pl.col('date_time').dt.strftime('%Y-%m-%d'))
    
    # Pandas
    df['date_time'] = df['date_time'].dt.strftime('%Y-%m-%d')
    

    Edit: added Polars