极地 0.16 更新
Since PR 6496 https://github.com/pola-rs/polars/pull/6496,已合并,您可以将混合偏移解析为 UTC,然后设置时区:
import polars as pl
pdf = pl.DataFrame([
{'name': 'BST 11:06', 'ts': '2022:06:27 11:06:12.16+01:00'},
{'name': 'GMT 7:06', 'ts': '2022:12:27 12:06:12.16+00:00'},
])
pdfts = pdf.with_columns(
pl.col('ts').str.strptime(
pl.Datetime(time_unit="us"), fmt="%Y:%m:%d %H:%M:%S.%f%z", utc=True)
.dt.convert_time_zone("Europe/London")
)
print(pdfts)
shape: (2, 2)
┌───────────┬─────────────────────────────┐
│ name ┆ ts │
│ --- ┆ --- │
│ str ┆ datetime[μs, Europe/London] │
╞═══════════╪═════════════════════════════╡
│ BST 11:06 ┆ 2022-06-27 11:06:12 BST │
│ GMT 7:06 ┆ 2022-12-27 12:06:12 GMT │
└───────────┴─────────────────────────────┘
旧版本:
您可以使用以下解决方法:删除 UTC 偏移量并本地化为预定义的时区。Note:仅当 UTC 偏移量和时区一致时,结果才是正确的。
timezone = "Europe/London"
pdfts = pdf.with_column(
plr.col('ts')
.str.replace("[+|-][0-9]{2}:[0-9]{2}", "")
.str.strptime(plr.Datetime, fmt="%Y:%m:%d %H:%M:%S%.f")
.dt.tz_localize(timezone)
)
print(pdf)
┌───────────┬──────────────────────────────┐
│ name ┆ ts │
│ --- ┆ --- │
│ str ┆ str │
╞═══════════╪══════════════════════════════╡
│ BST 11:06 ┆ 2022:06:27 11:06:12.16+01:00 │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ GMT 7:06 ┆ 2022:12:27 12:06:12.16+00:00 │
└───────────┴──────────────────────────────┘
print(pdfts)
┌───────────┬─────────────────────────────┐
│ name ┆ ts │
│ --- ┆ --- │
│ str ┆ datetime[ns, Europe/London] │
╞═══════════╪═════════════════════════════╡
│ BST 11:06 ┆ 2022-06-27 11:06:12.160 BST │
├╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ GMT 7:06 ┆ 2022-12-27 12:06:12.160 GMT │
└───────────┴─────────────────────────────┘
边注: 公平起见,pandas
也不处理混合 UTC 偏移量,除非您立即解析为 UTC(关键字utc=True
in pd.to_datetime
)。对于混合 UTC 偏移量,它会回退到使用一系列本机 Python 日期时间对象。这使得 Pandas 的很多时间序列功能都像dt
访问器不可用。