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

Pandas中int类型列转date类型列遇格式匹配错误求助

解决Pandas转换int日期列的问题
  • 错误原因:你使用的format='%d%m%Y'中,%Y匹配四位年份,但你的数据是两位年份;同时该格式要求日期字符串为8位(两位日+两位月+四位年),而你的数据是5位,导致格式不匹配报错。

  • 正确处理步骤:

    1. 将int类型列转为字符串,避免前导零丢失:
      df['Date'] = df['Date'].astype(str)
      
    2. 补全月份为两位(你的月份是一位数,需补零到两位,保证总长度为6位:两位日+两位月+两位年):
      # 拆分日、月、年并补零拼接
      df['Date_formatted'] = df['Date'].str[:2] + df['Date'].str[2:3].str.zfill(2) + df['Date'].str[3:]
      
      比如'10712'会被处理为'100712',对应日10、月07、年12。
    3. 使用%y(匹配两位年份)进行日期转换:
      df_date = pd.to_datetime(df['Date_formatted'], format='%d%m%y')
      
  • 简化写法(合并步骤):

    df_date = pd.to_datetime(
        df['Date'].astype(str).str[:2] + df['Date'].astype(str).str[2:3].str.zfill(2) + df['Date'].astype(str).str[3:],
        format='%d%m%y'
    )
    

注意:如果你的数据中存在月份是两位的情况(比如101212表示日10、月12、年12),上述补零操作不会影响它,因为str.zfill(2)对已经是两位的字符串无效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:50:42