Windows下Python解析无点西班牙语缩写月份日期报错如何解决
问题原因
该差异来源于Windows系统自身的西班牙语区域配置规则,与Python的locale库无关。Windows的西班牙语区域定义中,月份缩写默认携带末尾点号,而Ubuntu等Linux发行版的es_ES区域规则中月份缩写不带点,因此相同代码在不同系统表现不一致。
解决方案
- 方案1:使用第三方库
python-dateutil自定义月份映射(跨平台100%一致,最推荐)
首先安装依赖:pip install python-dateutil
代码示例:from dateutil import parser from dateutil.parser import parserinfo class SpanishMonthInfo(parserinfo): # 自定义西语月份缩写(不带点),按1-12月顺序排列 MONTHS = [ ("ene", "enero"), ("feb", "febrero"), ("mar", "marzo"), ("abr", "abril"), ("may", "mayo"), ("jun", "junio"), ("jul", "julio"), ("ago", "agosto"), ("sep", "septiembre"), ("oct", "octubre"), ("nov", "noviembre"), ("dic", "diciembre") ] # 解析示例 date_str = "18ene2021" parsed_date = parser.parse(date_str, parserinfo=SpanishMonthInfo()) print(parsed_date) # 输出 2021-01-18 00:00:00 - 方案2:修改Python内置解析规则,无额外依赖
直接给_strptime模块的月份缩写表添加不带点的西语条目,让解析器同时支持带点和不带点的格式:import locale from datetime import datetime import _strptime # 切换到西语locale locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8') # 给月份缩写表添加不带点的映射 month_abbr_list = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"] for idx, abbr in enumerate(month_abbr_list): _strptime._TimeRE_cache.month_abbr[abbr] = idx + 1 # 现在直接解析不带点的格式就不会报错了 print(datetime.strptime('18ene2021', '%d%b%Y')) # 输出 2021-01-18 00:00:00 - 方案3:仅需要生成不带点的西语月份缩写时,直接清理输出
比手动切割字符串更优雅,适配所有月份长度:# 生成时直接去掉末尾的点 month_abbr = datetime.strptime('2021-01-18', '%Y-%m-%d').strftime('%b').rstrip('.') print(month_abbr) # 输出 ene
内容的提问来源于stack exchange,提问作者Gonzalo AB
相关产品推荐
相关产品推荐

