Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 │
└───────────────────────────────┘
like image 667
Artur Avatar asked Oct 13 '25 05:10

Artur


2 Answers

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

like image 108
ErnestBidouille Avatar answered Oct 14 '25 19:10

ErnestBidouille


I eventually got this workaround but @ErnestBidouille answer was more of what I was looking for.

df.with_columns(pl.col('date_time').cast(pl.Date).cast(pl.String))
shape: (4, 1)
┌────────────┐
│ date_time  │
│ ---        │
│ str        │
╞════════════╡
│ 2007-04-19 │
│ 2007-05-02 │
│ 2007-05-03 │
│ 2007-05-03 │
└────────────┘
like image 24
Artur Avatar answered Oct 14 '25 19:10

Artur