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

Python:将DataFrame中‘feb-97’类日期转为指定日的datetime格式

将月份-年份格式字符串转为指定当月首尾日的datetime格式

前提准备

确保已导入pandas:

import pandas as pd

假设你的DataFrame包含目标列(示例列名为date_col),先创建样例数据方便测试:

df = pd.DataFrame({'date_col': ['feb-97', 'jan-02', 'dec-22']})

转为当月第一天

有两种简洁方式可以将字符串转为当月第一天的datetime格式:

  1. 默认解析(自动设为当月第一天)
    直接使用pd.to_datetime,指定匹配格式%b-%y(%b对应英文月份缩写,%y对应两位年份):
df['first_day'] = pd.to_datetime(df['date_col'], format='%b-%y')

执行后first_day列的值会是1997-02-01、2002-01-01、2022-12-01。

  1. 显式指定(更稳妥)
    用dt.floor('M')强制将日期对齐到当月第一天:
df['first_day'] = pd.to_datetime(df['date_col'], format='%b-%y').dt.floor('M')

转为当月最后一天

同样有两种常用方法:

  1. 利用Period对象的结束时间
    先将datetime转为月周期(Period),再提取周期的结束时间:
df['last_day'] = pd.to_datetime(df['date_col'], format='%b-%y').dt.to_period('M').dt.end_time

执行后last_day列的值会是1997-02-28、2002-01-31、2022-12-31。

  1. 使用MonthEnd偏移量
    导入MonthEnd偏移量,直接加到解析后的日期上:
from pandas.tseries.offsets import MonthEnd
df['last_day'] = pd.to_datetime(df['date_col'], format='%b-%y') + MonthEnd(0)

额外注意事项

  • 处理无效日期:如果列中存在不符合格式的字符串,可添加errors='coerce'参数将无效值转为NaT(缺失日期):
    df['first_day'] = pd.to_datetime(df['date_col'], format='%b-%y', errors='coerce')
    
  • 年份范围调整:pandas默认将两位年份00-69解析为2000-2069,70-99解析为1970-1999。若需自定义年份范围,可通过cutoff参数指定,比如将cutoff='2000-01-01',则两位年份00及以后解析为20xx,99及以前解析为19xx:
    df['first_day'] = pd.to_datetime(df['date_col'], format='%b-%y', cutoff='2000-01-01')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:20:31