Python日期转换异常:1月日期被识别为11月日期求助
日期转换错误:1月日期被识别为11月的解决方法
问题现象
处理日期字符串时,部分本应属于1月的日期被错误识别为11月:
- 字符串
1132008应转换为2008-01-13,实际输出2008-11-03 - 字符串
1122008应转换为2008-01-12,实际输出2008-11-02
错误转换的示例数据:
152008 2008-01-05 00:00:00 162008 2008-01-06 00:00:00 1122008 2008-11-02 00:00:00 1132008 2008-11-03 00:00:00 1202008 2008-01-20 00:00:00
当前使用的转换代码:
for i in old_games["Date"]: if len(str(i)) <= 4 and i > 900: i = str(i) + "2007" print(i) print(datetime.strptime(str(i), "%m%d%Y")) elif len(str(i)) <= 3 and i < 900 and not 109 < i < 120: i = str(i) + "2008" print(i) print(datetime.strptime(str(i), "%m%d%Y"))
错误原因
核心问题是日期字符串结构与解析格式不匹配:
- 你的日期字符串规则是:月份占1位(固定为1,代表1月),日期占1位(1-9日)或2位(10-31日),年份占4位
- 但代码中使用
%m%d%Y格式,该格式要求月份和日期各占2位。对于长度为7位的字符串(如1132008),代码会错误地把前两位11识别为11月,把接下来的3作为日期的第一位,最终解析出错误的日期。
解决方法
根据字符串长度拆分日期部分,对1位的月份补零后再用标准格式解析:
from datetime import datetime for i in old_games["Date"]: s = str(i) # 先按原逻辑补全年份 if len(s) <= 4 and int(s) > 900: s += "2007" elif len(s) <= 3 and int(s) < 900 and not 109 < int(s) < 120: s += "2008" # 根据长度解析日期 if len(s) == 6: # 1位月 + 1位日 + 4位年 → 补零为2位月+2位日+4位年 formatted_str = f"{s[0].zfill(2)}{s[1].zfill(2)}{s[2:]}" date = datetime.strptime(formatted_str, "%m%d%Y") elif len(s) == 7: # 1位月 + 2位日 + 4位年 → 补零为2位月+2位日+4位年 formatted_str = f"{s[0].zfill(2)}{s[1:3]}{s[3:]}" date = datetime.strptime(formatted_str, "%m%d%Y") else: # 其他长度按原格式解析(可根据实际情况调整) date = datetime.strptime(s, "%m%d%Y") print(s) print(date)
修改后,1132008会被转换为01132008,解析后得到正确的2008-01-13;1122008转换为01122008,解析后得到2008-01-12。
内容的提问来源于stack exchange,提问作者Petros Papadakos
相关产品推荐
相关产品推荐

