Python中贾拉历日期转公历日期的实现方法求助
解决贾拉历日期转公历的pandas报错问题
pandas的pd.to_datetime默认不支持波斯贾拉历的日期解析,直接传入۱۱ فروردین ۱۴۰۰这类格式的字符串自然会触发「未知日期格式」错误。下面是可行的解决方法:
方法一:使用专门的波斯历处理库jdatetime
这是最可靠的方案,jdatetime是针对波斯历开发的Python库,无需依赖系统locale设置。
- 先安装库:
pip install jdatetime
- 编写转换代码:
import jdatetime import pandas as pd # 定义波斯历月份到数字的映射 jalali_month_map = { "فروردین": 1, "اردیبهشت": 2, "خرداد": 3, "تیر": 4, "مرداد": 5, "شهریور": 6, "مهر": 7, "آبان": 8, "آذر": 9, "دی": 10, "بهمن": 11, "اسفند": 12 } # 目标贾拉历日期 jalali_str = "۱۱ فروردین ۱۴۰۰" # 拆分日期组件并转换为数字 day, month_name, year = jalali_str.split() year = int(year) month = jalali_month_map[month_name] day = int(day) # 转成贾拉历日期对象,再转换为公历 jalali_date = jdatetime.date(year, month, day) gregorian_date = jalali_date.togregorian() # 转为pandas Timestamp(可选) pd_date = pd.to_datetime(gregorian_date) print(gregorian_date) # 输出:2021-03-31 print(pd_date) # 输出:2021-03-31 00:00:00
如果需要批量处理DataFrame中的贾拉历日期列,可以封装成函数用apply处理:
def convert_jalali_to_gregorian(jalali_str): day, month_name, year = jalali_str.split() year = int(year) month = jalali_month_map[month_name] day = int(day) return jdatetime.date(year, month, day).togregorian() # 假设df包含名为jalali_date的列 df['gregorian_date'] = df['jalali_date'].apply(convert_jalali_to_gregorian) df['gregorian_date'] = pd.to_datetime(df['gregorian_date'])
方法二:依赖系统locale(不推荐)
如果你的系统已安装波斯语locale(如fa_IR),可以结合dateutil和locale尝试解析,但这种方法受系统环境限制,移植性差,且年份转换容易出问题,仅作参考:
import locale from dateutil.parser import parse import pandas as pd # 设置波斯语locale(需系统预先安装) locale.setlocale(locale.LC_TIME, 'fa_IR.UTF-8') # 解析日期(注意:此方法无法自动处理波斯历到公历的年份偏移,需手动调整) jalali_str = "۱۱ فروردین ۱۴۰۰" parsed_date = parse(jalali_str, dayfirst=True) # 波斯历1400对应公历2021,需手动修正年份 corrected_date = parsed_date.replace(year=parsed_date.year - 621) pd_date = pd.to_datetime(corrected_date)
内容的提问来源于stack exchange,提问作者Sahand Pourjavad
相关产品推荐
相关产品推荐

