如何用Python将时长字符串转换为以年为单位的数值
解决方案
单个字符串转换
用正则表达式提取年、月、天的数值,再按指定公式计算:
import re def convert_to_decimal_years(duration_str): # 提取字符串中的所有数字,对应年、月、天顺序 nums = list(map(int, re.findall(r'\d+', duration_str))) years, months, days = nums[0], nums[1], nums[2] # 按公式计算并保留两位小数 decimal_years = years + (months / 12) + (days / 365) return round(decimal_years, 2) # 测试示例 print(convert_to_decimal_years("9年3个月22天")) # 输出 9.31
批量处理列数据(如Pandas Series)
如果数据是Pandas的一列,用apply方法批量转换:
import pandas as pd # 模拟待处理列数据 data = pd.Series(["9年3个月22天", "5年6个月10天", "2年0个月15天"]) # 批量转换 converted_data = data.apply(convert_to_decimal_years) print(converted_data)
输出结果:
0 9.31 1 5.53 2 2.04 dtype: float64
说明
- 正则
r'\d+'会匹配字符串中所有连续数字,适配你给出的“X年X个月X天”固定格式。 - 严格按照公式
年数 + 月数/12 + 天数/365计算,最后用round保留两位小数得到目标结果。
内容的提问来源于stack exchange,提问作者Mallesh
相关产品推荐
相关产品推荐

