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

使用pd.to_datetime转换西语格式时间字符串报错,求解决方法

解决西班牙语日期字符串转datetime的问题

针对你遇到的格式为"25 de mayo de 2023 14:53 hs."的日期字符串转换问题,有以下几种可行方案:

方案一:指定格式并设置西班牙语locale

Pandas的pd.to_datetime支持通过format参数匹配自定义格式,结合西班牙语locale可以识别月份名称(如mayo):

import pandas as pd
import locale

# 根据操作系统设置对应的西班牙语locale
# Windows系统使用:locale.setlocale(locale.LC_TIME, 'Spanish_Spain.1252')
# Linux/macOS系统使用:locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')

# 直接按指定格式转换
df['Fecha_de_venta'] = pd.to_datetime(
    df['Fecha_de_venta'],
    format="%d de %B de %Y %H:%M hs."
)

方案二:先清洗字符串再转换

手动去除冗余字符并调整格式,再进行转换,避免locale依赖问题:

import pandas as pd
import locale

locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')

# 1. 去掉末尾的" hs."
df['Fecha_limpia'] = df['Fecha_de_venta'].str.replace(r' hs.$', '', regex=True)
# 2. 替换" de "为空格,简化格式
df['Fecha_limpia'] = df['Fecha_limpia'].str.replace(' de ', ' ')

# 按简化后的格式转换
df['Fecha_de_venta'] = pd.to_datetime(df['Fecha_limpia'], format="%d %B %Y %H:%M")

方案三:使用第三方库自动识别

如果不想处理locale和格式,可使用dateparser库自动识别多语言日期:

import pandas as pd
from dateparser import parse

# 自动识别日期格式
df['Fecha_de_venta'] = df['Fecha_de_venta'].apply(parse)

注:需先安装库:pip install dateparser

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:12:41