尝试将 pl.Date 列按原样转换为 UNIX 纪元,没有任何时区偏移:
import datetime
import polars as pl
df = pl.DataFrame(
{'Date': [datetime.datetime.now().date()]}
)
转换为日期时间时的正确时间 (00:00:00):
df.with_columns(
pl.col("Date").cast(pl.Datetime)
)
┌─────────────────────┐
│ Date │
│ --- │
│ datetime[μs] │
╞═════════════════════╡
│ 2023-06-10 00:00:00 │
└─────────────────────┘
转换为时间戳时时间不正确:
datetime.datetime.fromtimestamp(
df.with_columns(
pl.col("Date").cast(pl.Datetime).dt.timestamp("ms").truediv(1_000)
).item()
)
datetime.datetime(2023, 6, 10, 8, 0) # (08:00:00)
按照建议,不转换为日期时间也会产生错误的时间。
pl.col("Date").dt.timestamp("ms").truediv(1_000)
请注意,如果您不设置时区(原始日期时间),普通 Python 日期时间默认为“本地”时间。相比之下,Polars 假设朴素的日期时间类似于 UTC(Pandas 也是如此)。 通过设置时区保持一致,例如世界标准时间:
from datetime import datetime, timezone
import polars as pl
df = pl.DataFrame(
{'Date': [datetime.now(timezone.utc).date()]}
)
df = df.with_columns(
pl.col("Date").cast(pl.Datetime).dt.timestamp("ms").truediv(1_000).alias("Unix")
)
print(df)
# shape: (1, 2)
# ┌────────────┬──────────┐
# │ Date ┆ Unix │
# │ --- ┆ --- │
# │ date ┆ f64 │
# ╞════════════╪══════════╡
# │ 2023-06-10 ┆ 1.6864e9 │
# └────────────┴──────────┘
print(datetime.fromtimestamp(df["Unix"][0], timezone.utc))
# 2023-06-10 00:00:00+00:00