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

基于日期范围创建日期列

基于日期范围创建日期列

看起来你需要把缩写格式的日期转换成指定年度区间(2021年4月1日至2022年3月31日)内的标准日期列,我给你两种常用工具的解决方案,你可以根据自己的使用场景选择:

Python(Pandas)方案

核心思路是:先拆分日和月份缩写,根据月份判断所属年份(4-12月归为2021年,1-3月归为2022年),最后组合成指定格式的日期。

import pandas as pd
from datetime import datetime

# 构造你的原始数据
df = pd.DataFrame({
    'colA': ['12 may', '3 sep', '4 mar']
})

# 定义日期解析函数
def parse_custom_date(date_str):
    day_str, month_abbr = date_str.split()
    # 将月份缩写转为数字(支持英文缩写)
    month_num = datetime.strptime(month_abbr, '%b').month
    # 根据月份判断年份
    target_year = 2021 if 4 <= month_num <= 12 else 2022
    # 生成日期对象并转为指定格式
    full_date = datetime(target_year, month_num, int(day_str))
    return full_date.strftime('%d/%m/%Y')

# 生成目标日期列
df['date_col'] = df['colA'].apply(parse_custom_date)

print(df)

运行后输出结果和你期望的一致:

colA    date_col
0  12 may  12/05/2021
1   3 sep  03/09/2021
2   4 mar  04/03/2022

R(lubridate + dplyr)方案

利用lubridate的日期处理能力,配合dplyr的管道操作,同样按照月份判断年份来生成目标日期:

library(lubridate)
library(dplyr)
library(stringr)

# 原始数据
df <- data.frame(colA = c("12 may", "3 sep", "4 mar"), stringsAsFactors = FALSE)

# 处理日期列
df <- df %>%
  mutate(
    day = as.integer(word(colA, 1)),
    month = match(word(colA, 2), month.abb),
    year = ifelse(month %in% 4:12, 2021, 2022),
    date_col = format(dmy(paste(day, month, year)), "%d/%m/%Y")
  ) %>%
  select(colA, date_col)

print(df)

注意事项

如果你的月份缩写不是英文的(比如中文缩写),需要调整月份映射逻辑,比如自定义一个月份缩写和数字的对应字典/向量,替换代码中的月份转换部分即可。

备注:内容来源于stack exchange,提问作者asd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.17 12:44:32