polars.Expr.str.strptime#

Expr.str.strptime(
dtype: PolarsTemporalType,
format: str | None = None,
*,
strict: bool = True,
exact: bool = True,
cache: bool = True,
ambiguous: Ambiguous | Expr = 'raise',
) Expr[source]#

将字符串列转换为日期/日期时间/时间列。

Parameters:
dtype

要转换成的数据类型。可以是Date、Datetime或Time。

format

用于转换的格式。请参阅chrono crate文档以获取完整的规范。示例:"%Y-%m-%d %H:%M:%S"。如果设置为None(默认值),则从数据中推断格式。

strict

如果任何转换失败,则引发错误。

exact

需要精确的格式匹配。如果为False,则允许格式在目标字符串中的任何位置匹配。转换为Time类型始终是精确的。

注意

使用 exact=False 会引入性能损失 - 事先清理你的数据几乎肯定会更高效。

cache

使用唯一的、转换后的日期缓存来应用日期时间转换。

ambiguous

确定如何处理模糊的日期时间:

  • 'raise' (默认): 抛出异常

  • 'earliest': 使用最早的日期时间

  • 'latest': 使用最新的日期时间

  • 'null': 设置为null

注释

当转换为Datetime类型时,如果提供了格式字符串,则从格式字符串中推断时间单位,例如:"%F %T%.3f" => Datetime("ms")。如果未找到小数秒部分,则默认为"us"

示例

处理一致的格式:

>>> s = pl.Series(["2020-01-01 01:00Z", "2020-01-01 02:00Z"])
>>> s.str.strptime(pl.Datetime, "%Y-%m-%d %H:%M%#z")
shape: (2,)
Series: '' [datetime[μs, UTC]]
[
        2020-01-01 01:00:00 UTC
        2020-01-01 02:00:00 UTC
]

处理不同的格式。

>>> s = pl.Series(
...     "date",
...     [
...         "2021-04-22",
...         "2022-01-04 00:00:00",
...         "01/31/22",
...         "Sun Jul  8 00:34:60 2001",
...     ],
... )
>>> s.to_frame().select(
...     pl.coalesce(
...         pl.col("date").str.strptime(pl.Date, "%F", strict=False),
...         pl.col("date").str.strptime(pl.Date, "%F %T", strict=False),
...         pl.col("date").str.strptime(pl.Date, "%D", strict=False),
...         pl.col("date").str.strptime(pl.Date, "%c", strict=False),
...     )
... ).to_series()
shape: (4,)
Series: 'date' [date]
[
        2021-04-22
        2022-01-04
        2022-01-31
        2001-07-08
]