将 pl.Date 转换为 Unix 纪元

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

尝试将 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 datetime python-polars
1个回答
3
投票

请注意,如果您不设置时区(原始日期时间),普通 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

	
© www.soinside.com 2019 - 2024. All rights reserved.