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

如何用Python将特定编码的CSV数据转换为月/年/日格式?

Python处理CSV编码转月/年/日格式方案

核心思路

先编写单个编码的解码函数,再批量处理CSV中的2万+行数据。解码逻辑严格匹配给定规则:

  • 第1位解析月份:数字1-9对应1-9月,X/Y/Z对应10/11/12月
  • 第2位解析年份:6-9对应2016-2019,0-5对应2020-2025
  • 第3位解析日期:数字1-9对应1-9日,A-Y(不含I)对应10-31日

1. 单个编码解码函数

def decode_date_code(code):
    # 解析月份
    month_char = code[0]
    if month_char.isdigit():
        month = int(month_char)
    else:
        month_map = {'X': 10, 'Y': 11, 'Z': 12}
        month = month_map[month_char]
    
    # 解析年份
    year_char = code[1]
    if year_char in '6789':
        year = 2010 + int(year_char)
    else:
        year = 2020 + int(year_char)
    
    # 解析日期(生成A-Y不含I的映射表)
    day_char = code[2]
    if day_char.isdigit():
        day = int(day_char)
    else:
        day_map = {}
        current_day = 10
        for ascii_code in range(ord('A'), ord('Z') + 1):
            char = chr(ascii_code)
            if char == 'I':
                continue
            day_map[char] = current_day
            current_day += 1
        day = day_map[day_char]
    
    return f"{month}/{year}/{day}"

测试示例:

  • 输入X070A017F57H → 输出10/2020/7
  • 输入Z9A0A0PPF57H → 输出12/2019/10

2. 批量处理CSV文件

针对2万+行数据,推荐两种方案:

方案一:用Pandas高效处理(简洁快速)

import pandas as pd

# 读取CSV(假设文件仅含编码列,无表头)
df = pd.read_csv('input.csv', header=None, names=['code'])

# 批量解码
df['decoded_date'] = df['code'].apply(decode_date_code)

# 保存结果到新CSV
df.to_csv('output.csv', index=False)

方案二:用原生CSV模块(无需额外依赖)

import csv

with open('input.csv', 'r') as infile, open('output.csv', 'w', newline='') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    # 写入表头
    writer.writerow(['原始编码', '解码日期'])
    
    for row in reader:
        if row:  # 跳过空行
            code = row[0]
            decoded_date = decode_date_code(code)
            writer.writerow([code, decoded_date])

异常处理优化(可选)

如果存在不符合规则的编码,可在解码函数中加入异常捕获,避免程序中断:

def decode_date_code(code):
    try:
        # 原解码逻辑...
    except (KeyError, IndexError) as e:
        print(f"无效编码:{code},错误原因:{str(e)}")
        return "无效编码"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:23:14