ComputeError: Different timezones found during 'strptime' operation.
我如何说服它成功转换这些?
(理想情况下处理不同时区以及从夏季到冬季的时间变化)然后如何将这些时间戳转换回正确的本地时钟时间以进行显示?
请注意,虽然时间戳字符串仅显示偏移量,但元数据中有一个 exif 字段“时区城市”以及仅包含本地(原始)时间戳的字段
import polars as plr
testdata=[
{'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'},
]
pdf = plr.DataFrame(testdata)
pdfts = pdf.with_column(plr.col('ts').str.strptime(plr.Datetime, fmt = "%Y:%m:%d %H:%M:%S.%f%z"))
print(pdf)
print(pdfts)
看起来我需要使用 tz_convert,但我看不到如何将其添加到转换表达式中,以及相关文档页看起来只是 404
PR 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.to_datetime("%Y:%m:%d %H:%M:%S%.f%z")
.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.160 BST │
│ GMT 7:06 ┆ 2022-12-27 12:06:12.160 GMT │
└───────────┴─────────────────────────────┘
注意: 仅当 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
中的关键字
pd.to_datetime
)。对于混合 UTC 偏移量,它会回退到使用一系列本机 Python 日期时间对象。这使得很多 pandas 时间序列功能(例如
dt
访问器)不可用。
第一步是使用
extract
正则表达式将偏移量与其余时间分开。 偏移量分为小时和分钟(包括符号)。 然后,我们只需将第一步中的日期时间组件作为简单时间,添加/减去偏移量,将其本地化为 UTC,然后将其设为所需的时区(在本例中为欧洲/伦敦)。 **(我将
strptime
加载为 pl 而不是 plr,因此根据需要进行调整)
polars