Update: .str.to_datetime() https://pola-rs.github.io/polars/py-polars/html/reference/expressions/api/polars.Expr.str.to_datetime.html#polars.Expr.str.to_datetime可以像极地一样使用v0.17.10 https://github.com/pola-rs/polars/releases/tag/py-0.17.10
df = pl.from_repr("""
┌─────┬──────────────────┐
│ id ┆ event_date │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════════════════╡
│ 1 ┆ 27 July 2020 │
│ 2 ┆ 31 December 2020 │
└─────┴──────────────────┘
""")
df.with_columns(
pl.col("event_date").str.to_datetime("%d %B %Y")
)
shape: (2, 2)
┌─────┬─────────────────────┐
│ id ┆ event_date │
│ --- ┆ --- │
│ i64 ┆ datetime[μs] │
╞═════╪═════════════════════╡
│ 1 ┆ 2020-07-27 00:00:00 │
│ 2 ┆ 2020-12-31 00:00:00 │
└─────┴─────────────────────┘
将字符串转换为日期/日期时间的最简单方法是使用 Polars 自己的strptime https://pola-rs.github.io/polars/py-polars/html/reference/expressions/api/polars.Expr.str.strptime.html函数(而不是 Python 中的同名函数)datetime
模块)。
例如,让我们从这个数据开始。
import polars as pl
df = pl.DataFrame({
'date_str': ["27 July 2020", "31 December 2020"]
})
print(df)
shape: (2, 1)
┌──────────────────┐
│ date_str │
│ --- │
│ str │
╞══════════════════╡
│ 27 July 2020 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 31 December 2020 │
└──────────────────┘
要转换,请使用 Polarsstrptime https://pola-rs.github.io/polars/py-polars/html/reference/expressions/api/polars.Expr.str.strptime.html功能。
df.with_columns(pl.col('date_str').str.strptime(pl.Date, fmt='%d %B %Y').cast(pl.Datetime))
shape: (2, 1)
┌─────────────────────┐
│ date_str │
│ --- │
│ datetime[μs] │
╞═════════════════════╡
│ 2020-07-27 00:00:00 │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2020-12-31 00:00:00 │
└─────────────────────┘
请注意,我们不需要用破折号替换空格。我已将结果转换为日期时间(根据您的问题),但您也许可以使用日期。
目前,apply
当返回类型是 python Date/Datetime 对象时该方法不起作用,但是有一个request https://github.com/pola-rs/polars/issues/3022为了这。也就是说,最好使用 Polarsstrptime
。会比调用python快很多datetime
code.
Edit:截至极地0.13.19
, the apply
方法会自动将Python日期/日期时间转换为Polars日期/日期时间。