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

Pandas如何将间隔天数转换为天周月年最优单位字符串

间隔天数转时间单位字符串实现方案

核心逻辑是设置合理的天数容错阈值,按照年>月>周>天的优先级从粗粒度到细粒度判断,当实际天数和某粒度换算后的取整值差值在容错范围内时,直接选用该粒度单位,避免出现31天返回4Weeks这类不符合日常认知的结果。


规则预设

  • 换算系数:1周=7天,1月=30天,1年=365天
  • 容错阈值默认设为5天:实际天数和高一级单位的整值换算结果差不超过5天时,优先选用高一级单位,抵消自然月、平闰年带来的天数差
  • 单复数规则:数值为1时用单位单数,大于1时用单位复数,可按需调整

实现代码

import pandas as pd

def convert_days(days: int, tolerance: int = 5) -> str:
    # 优先匹配年粒度
    year_num = round(days / 365)
    if year_num >= 1 and abs(days - year_num * 365) <= tolerance:
        unit = "Year" if year_num == 1 else "Years"
        return f"{year_num}{unit}"
    # 匹配月粒度
    month_num = round(days / 30)
    if month_num >= 1 and abs(days - month_num * 30) <= tolerance:
        unit = "Month" if month_num == 1 else "Months"
        return f"{month_num}{unit}"
    # 匹配周粒度
    week_num = round(days / 7)
    if week_num >= 1:
        unit = "Week" if week_num == 1 else "Weeks"
        return f"{week_num}{unit}"
    # 剩余结果返回天粒度
    unit = "Day" if days == 1 else "Days"
    return f"{days}{unit}"

# 测试示例数据
daysSeries = pd.Series([2, 13,29,31,91,180,367,725],dtype="int64")
result = daysSeries.apply(convert_days).tolist()
print(result)

调整说明

运行上述代码输出结果为:
['2Days', '2Weeks', '1Month', '1Month', '3Months', '6Months', '1Year', '2Years']
和需求给出的示例差异仅在3Month/2Year的单复数后缀,如果需要完全匹配示例格式,直接把函数里月、年单位的复数判断逻辑去掉,固定返回Month/Year后缀即可。
如果需要更精准的换算,可以把月换算系数改成30.44、年改成365.25,对应调整容错阈值就能适配更严格的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:15:41