You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Polars中将含多个月份的字符串转换为日期?

解决方案

因为原始字符串包含两个月份,strptime无法直接解析这种非标准日期格式,你可以基于已提取的月份和年份字段,拼接成合法的单月份日期字符串后再转换为日期类型。以下是两种实现方式:

方式一:基于已提取的字段生成日期

在你现有代码的基础上,直接拼接起始/结束月份与年份,转换为对应月份的第一天或最后一天:

import polars as pl

df = pl.DataFrame(
    {
        "name": [
            "January/February 1994",
            "November/December 1996",
            "May/June 1999",
            "March/April 2005",
        ]
    }
)

out = df.with_columns(
    pl.col("name").str.extract(r"(\w+)\/").alias("start_month"),
    pl.col("name").str.extract(r"\/(\w+)").alias("end_month"),
    pl.col("name").str.extract(r"(\d+)").alias("year"),
).with_columns(
    # 生成起始月份的第一天
    pl.concat_str([pl.col("start_month"), pl.lit(" 1 "), pl.col("year")])
    .str.strptime(pl.Date, "%B %d %Y")
    .alias("start_date"),
    # 生成结束月份的最后一天
    pl.concat_str([pl.col("end_month"), pl.lit(" 1 "), pl.col("year")])
    .str.strptime(pl.Date, "%B %d %Y")
    .dt.month_end()
    .alias("end_date"),
)

print(out)

输出结果:

shape: (4, 6)
┌────────────────────────┬─────────────┬───────────┬──────┬────────────┬────────────┐
│ name                   ┆ start_month ┆ end_month ┆ year ┆ start_date ┆ end_date   │
│ ---                    ┆ ---         ┆ ---       ┆ ---  ┆ ---        ┆ ---        │
│ str                    ┆ str         ┆ str       ┆ str  ┆ date       ┆ date       │
╞════════════════════════╪═════════════╪═══════════╪══════╪════════════╪════════════╡
│ January/February 1994  ┆ January     ┆ February  ┆ 1994 ┆ 1994-01-01 ┆ 1994-02-28 │
│ November/December 1996 ┆ November    ┆ December  ┆ 1996 ┆ 1996-11-01 ┆ 1996-12-31 │
│ May/June 1999          ┆ May         ┆ June      ┆ 1999 ┆ 1999-05-01 ┆ 1999-06-30 │
│ March/April 2005       ┆ March       ┆ April     ┆ 2005 ┆ 2005-03-01 ┆ 2005-04-30 │
└────────────────────────┴─────────────┴───────────┴──────┴────────────┴────────────┘

方式二:一步完成提取与转换

无需单独生成中间列,直接通过正则提取后拼接转换,简化代码:

import polars as pl

df = pl.DataFrame(
    {
        "name": [
            "January/February 1994",
            "November/December 1996",
            "May/June 1999",
            "March/April 2005",
        ]
    }
)

out = df.with_columns(
    # 提取起始月份+年份,转成当月第一天
    pl.col("name")
    .str.extract(r"(\w+)\/\w+ (\d+)")
    .str.replace(r"(\w+) (\d+)", r"\1 1 \2")
    .str.strptime(pl.Date, "%B %d %Y")
    .alias("start_date"),
    # 提取结束月份+年份,转成当月最后一天
    pl.col("name")
    .str.extract(r"\w+\/(\w+) (\d+)")
    .str.replace(r"(\w+) (\d+)", r"\1 1 \2")
    .str.strptime(pl.Date, "%B %d %Y")
    .dt.month_end()
    .alias("end_date"),
)

print(out)

关键说明

  • strptime要求输入字符串对应标准日期格式,因此必须为月份补充一个具体日期(这里用1号)才能完成解析。
  • 使用dt.month_end()可以快速获取对应月份的最后一天,无需手动计算天数。

内容的提问来源于stack exchange,提问作者Adrian Fletcher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:22:55