将时区感知日期时间列转换为具有 UTC 时间偏移量的字符串

问题描述 投票:0回答:1

更新:已通过pull/6673

修复

我有以下数据框:

df = (
    pl.DataFrame(
        {
            "int": [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")
    )
)

给出:

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

我想将此日期时间类型转换为带有时区指示符的字符串,例如

2010-02-01 00:00:00+01:00

我尝试了以下方法:

df.with_columns(pl.col("date").dt.to_string("%Y-%m-%d %H:%M:%S%z"))

这给出了以下错误:

pyo3_runtime.PanicException: a formatting trait implementation returned an error: Error

我想要的输出如下所述,这是当您将日期时间列转换为 pandas 中的字符串类型(格式为

"%Y-%m-%d %H:%M:%S%z"
)时得到的结果:

┌─────┬──────────────────────────┐
│ int ┆ date                     │
│ --- ┆ ---                      │
│ i64 ┆ str                      │
╞═════╪══════════════════════════╡
│ 1   ┆ 2010-02-01 00:00:00+0100 │
│ 2   ┆ 2010-02-01 01:00:00+0100 │
│ 3   ┆ 2010-02-01 02:00:00+0100 │
└─────┴──────────────────────────┘

有什么办法可以实现这个结果吗?指定格式时,在末尾省略

%z
是可行的,但 UTC 时间偏移是我需要的。

python datetime timezone strftime python-polars
1个回答
3
投票

py-polars v0.16.3 修复了问题:

import polars as pl

df = (
    pl.DataFrame(
        {
            "int": [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")
    )
)

print(
      df.with_columns(pl.col("date").dt.to_string("%Y-%m-%d %H:%M:%S%z"))
)

shape: (3, 2)
┌─────┬──────────────────────────┐
│ int ┆ date                     │
│ --- ┆ ---                      │
│ i64 ┆ str                      │
╞═════╪══════════════════════════╡
│ 1   ┆ 2010-02-01 00:00:00+0100 │
│ 2   ┆ 2010-02-01 01:00:00+0100 │
│ 3   ┆ 2010-02-01 02:00:00+0100 │
└─────┴──────────────────────────┘

注释

  1. 要获取以冒号分隔的 UTC 偏移量,请使用
    %:z
    。另请参阅 Rust / chrono 格式指令
  2. convert_time_zone
    是新的 with_time_zone。我希望它保持这样;-)
© www.soinside.com 2019 - 2024. All rights reserved.