You need to enable JavaScript to run this app. Python如何不受输入格式限制 将日期转换为指定格式
优惠活动
大模型
产品
解决方案
定价
更多

Python如何不受输入格式限制 将日期转换为指定格式

无分隔符日期统一转换解决方案

整体采用「预处理+通用解析」两步实现,先把无分隔符的特殊格式转换为dateutil可识别的结构,再用现有能力统一输出即可。

核心实现步骤

  • 第一步:对输入字符串做清洗,移除冗余特殊字符,统一大小写方便匹配
  • 第二步:通过正则匹配不同的无分隔符日期模式,提前转换为带分隔符的标准化结构
  • 第三步:将预处理后的字符串交给dateutil.parser解析,最终格式化输出为YYYY-MM-DD格式

关键匹配逻辑

针对你给出的特殊场景,预设的匹配规则如下:

  • 8位纯数字:优先按YYYYMMDD规则校验(月日范围合法则直接转换),如果不合法则按YYYYDDMM规则校验转换,覆盖20201120、20202011这类场景
  • 带英文月份缩写的混合字符串:先匹配3位英文月份缩写映射为数字月份,再提取字符串中的数字段分别作为年、日,覆盖202020Nov这类场景
  • 本身带分隔符的格式直接跳过预处理,交给dateutil原生能力处理

可运行代码示例

from dateutil import parser
import re

# 月份缩写映射表
MONTH_MAP = {
    'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
    'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12
}

def preprocess_date(date_input: str) -> str:
    # 清洗非数字、非字母字符,统一转小写
    clean_str = re.sub(r'[^a-z0-9]', '', date_input.lower())
    
    # 匹配带英文月份的场景
    month_match = re.search(r'[a-z]{3}', clean_str)
    if month_match:
        month_abbr = month_match.group()
        month_num = MONTH_MAP.get(month_abbr)
        if not month_num:
            return date_input
        # 提取所有数字部分
        num_parts = re.findall(r'\d+', clean_str)
        full_num = ''.join(num_parts)
        # 取4位为年,剩余2位为日
        year = full_num[:4] if len(full_num) >=4 else f"20{full_num[-2:]}"
        day = full_num[4:6] if len(full_num) >=6 else full_num[:2]
        return f"{year}-{month_num:02d}-{day:02d}"
    
    # 匹配8位纯数字场景
    if len(clean_str) == 8 and clean_str.isdigit():
        # 先校验YYYYMMDD格式
        if 1 <= int(clean_str[4:6]) <= 12 and 1 <= int(clean_str[6:8]) <= 31:
            return f"{clean_str[:4]}-{clean_str[4:6]}-{clean_str[6:8]}"
        # 再校验YYYYDDMM格式
        if 1 <= int(clean_str[6:8]) <= 12 and 1 <= int(clean_str[4:6]) <= 31:
            return f"{clean_str[:4]}-{clean_str[6:8]}-{clean_str[4:6]}"
    
    # 其他带分隔符的场景直接返回原输入
    return date_input

def convert_to_standard(date_input: str) -> str:
    preprocessed = preprocess_date(date_input)
    date_obj = parser.parse(preprocessed)
    return date_obj.strftime("%Y-%m-%d")

测试结果

针对你给出的所有示例,运行结果如下:

  • convert_to_standard("2020/11/20") → 2020-11-20
  • convert_to_standard("20201120") → 2020-11-20
  • convert_to_standard("20202011") → 2020-11-20
  • convert_to_standard("11/20/2020") → 2020-11-20
  • convert_to_standard("202020Nov") → 2020-11-20

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 17:24:01