如何将pandas中%B %d格式日期列转换为带当年年份的标准日期
pandas无年份日期转换补全当前年份解决方案
使用pd.to_datetime解析不含年份的「月份全称 日」格式字符串时,默认会用1900年作为补全年份,要替换为当前年份可按以下方案实现:
基础方案(直接补当前年份)
import pandas as pd from datetime import datetime # 获取当前年份 current_year = datetime.now().year # 先解析日期,再替换年份 df['Date'] = pd.to_datetime(df['Date'], format='%B %d').apply(lambda x: x.replace(year=current_year))
如果需要最终输出为YYYY-mm-dd格式的字符串,可在代码末尾追加.dt.strftime('%Y-%m-%d')即可。
进阶方案(自动适配跨年场景)
如果存在解析后的日期晚于当前实际日期的场景(例如当前是2024年1月,解析December 31时直接补2024年会得到未来日期,实际应为2023年的日期),可增加年份自动调整逻辑:
import pandas as pd from datetime import datetime current_date = datetime.now() current_year = current_date.year def adjust_year(dt): temp_dt = dt.replace(year=current_year) # 若替换后为未来日期,自动回退一年 if temp_dt > current_date: return temp_dt.replace(year=current_year - 1) return temp_dt df['Date'] = pd.to_datetime(df['Date'], format='%B %d').apply(adjust_year)
注意:如果你的系统默认 locale 不是英文,
%B无法识别英文月份全称,可在解析前临时设置时间 locale 为英文:import locale # Windows 系统用这行 locale.setlocale(locale.LC_TIME, 'English_US') # Linux/Mac 系统用这行 # locale.setlocale(locale.LC_TIME, 'en_US.UTF-8')
内容的提问来源于stack exchange,提问作者CaioT
相关产品推荐
相关产品推荐

