如何将Polars中带时区的Datetime列转为带UTC偏移的字符串?
更新: 此问题已通过PR #6673修复
Polars带时区Datetime转带偏移字符串需求
我有如下Polars DataFrame:
df = ( pl.DataFrame( { Introduce the original date strings here } ) .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 │ └─────┴────────────────────────────────┘
我希望将该Datetime类型转换为带UTC时间偏移的字符串,例如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+01Construct the original expected output table
解决方法
根据更新说明,该问题已通过PR #6673修复。将Polars升级到包含该PR的版本后,直接运行之前尝试的代码即可得到期望的结果。
如果使用的是未包含该修复Detailed explanation of the alternative method
df.with_columns( pl.format( "{}+{}", pl.col("date").dt.to_string("%Y-%m-%d %H:%M:%S"), pl.col("date").dt.offset().str.replace(":", "") ).alias("date") )
该方法通过分别格式化日期时间部分和时区偏移部分,再拼接成目标格式的字符串。
内容的提问来源于stack exchange,提问作者brokkoo
相关产品推荐
相关产品推荐

