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 │
└───────────────────────────────┘
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
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 │
└────────────┘
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With