You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Polars中从带时区的datetime列提取正确日期?

问题解决方法

1. 正确提取时区感知的日期

在Polars中,cast(pl.Date)会直接基于UTC时区转换日期,而非当前列绑定的时区。要实现类似Pandas中dt.date的效果,提取对应时区的日期,需使用dt.date()方法:

df = df.with_columns(
    pl.col("date").dt.date().alias("valueDay")
)

执行后会得到符合预期的结果:

shape: (3, 3)
┌─────────┬────────────────────────────────┬────────────┐
│ integer ┆ date                           ┆ valueDay   │
│ ---     ┆ ---                            ┆ ---        │
│ i64     ┆ datetime[μs, Europe/Amsterdam] ┆ date       │
╞═════════╪════════════════════════════════╪════════════╡
│ 1       ┆ 2010-02-01 00:00:00 CET        ┆ 2010-02-01 │
│ 2       ┆ 2010-02-01 01:00:00 CET        ┆ 2010-02-01 │
│ 3       ┆ 2010-02-01 02:00:00 CET        ┆ 2010-02-01 │
└─────────┴────────────────────────────────┴────────────┘

2. 链式调用优化代码

Polars原生支持方法链式调用,无需重复赋值给df,可以将所有操作串联,代码更简洁:

df = (
    pl.DataFrame(
        {
            "integer": [1, 2, 3], 
            "date": [
                "2010-01-31T23:00:00+00:00",
                "2010-02-01T00:00:00+00:00",
                "2010-02-01T01:00:00+00:00"
            ]
        }
    )
    .with_columns(
        pl.col("date").str.to_datetime().dt.convert_time_zone("Europe/Amsterdam")
    )
    .with_columns(
        pl.col("date").dt.date().alias("valueDay")
    )
)

也可以合并两个with_columns操作,进一步简化:

df = (
    pl.DataFrame(
        {
            "integer": [1, 2, 3], 
            "date": [
                "2010-01-31T23:00:00+00:00",
                "2010-02-01T00:00:00+00:00",
                "2010-02-01T01:00:00+00:00"
            ]
        }
    )
    .with_columns(
        pl.col("date").str.to_datetime().dt.convert_time_zone("Europe/Amsterdam").alias("date"),
        pl.col("date").str.to_datetime().dt.convert_time_zone("Europe/Amsterdam").dt.date().alias("valueDay")
    )
)

内容的提问来源于stack exchange,提问作者brokkoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:10:20