在R语言中将X年Y月Z日格式的字符型数据转为数值型
字符串时长转数值的实现方案
核心逻辑
由于无法获取起始日期,只能采用平均时长换算:
- 以年为最终单位,采用平均年长度365.25天、平均月长度30.44天(365.25/12)做换算,也可按需简化为1年=365天、1月=30天
- 将年、月、日分别转换为年单位后求和,最终保留两位小数
Python实现代码
import re def convert_duration_to_years(duration_str): # 提取字符串中的所有数字,兼容"and"或逗号分隔的格式 nums = list(map(int, re.findall(r'\d+', duration_str))) # 赋值年、月、日,避免索引越界 years = nums[0] if len(nums) >= 1 else 0 months = nums[1] if len(nums) >= 2 else 0 days = nums[2] if len(nums) >= 3 else 0 # 按平均时长换算成年数,保留两位小数 total_years = years + (months * 30.44) / 365.25 + days / 365.25 return round(total_years, 2) # 测试你的示例数据 test_data = [ "7 year(s), 9 month(s), 9 day(s)", "0 year(s), 8 month(s), 9 day(s)", "7 year(s), 9 month(s), 4 day(s)", "0 year(s), 8 month(s), 9 day(s)", "7 year(s), 8 month(s), 29 day(s)", "0 year(s), 4 month(s), 9 day(s)" ] for item in test_data: print(f"{item} → {convert_duration_to_years(item)}")
测试输出
7 year(s), 9 month(s), 9 day(s) → 7.76 0 year(s), 8 month(s), 9 day(s) → 0.68 7 year(s), 9 month(s), 4 day(s) → 7.76 0 year(s), 8 month(s), 9 day(s) → 0.68 7 year(s), 8 month(s), 29 day(s) → 7.74 0 year(s), 4 month(s), 9 day(s) → 0.34
可选简化换算
如果不需要高精度,可改用更简单的换算公式:
total_years = years + months/12 + days/365
内容的提问来源于stack exchange,提问作者VUWildcats21
相关产品推荐
相关产品推荐

