如何将形如"4w 2d"的字符串转换为timedelta类型?
高效转换时长字符串为timedelta的方法
你提到的拆分后判断后缀的思路可行,但可以通过字典映射+正则批量提取的方式让代码更简洁高效,避免冗余的if-else分支。
方法一:正则匹配+字典映射
利用正则一次性提取所有数字与对应单位,通过字典映射到timedelta的参数名,直接构造对象,代码简洁且扩展性强。
示例代码:
import re from datetime import timedelta def str_to_timedelta(duration_str): # 单位到timedelta参数的映射,周需转天(timedelta无weeks参数) unit_map = { 'w': 'days', 'd': 'days', 'h': 'hours', 'm': 'minutes' } # 匹配所有"数字+单位"的组合 matches = re.findall(r'(\d+)([wdhm])', duration_str) delta_kwargs = {} for num, unit in matches: key = unit_map[unit] value = int(num) * 7 if unit == 'w' else int(num) # 累加同单位数值(支持输入含多个同单位的情况) delta_kwargs[key] = delta_kwargs.get(key, 0) + value return timedelta(**delta_kwargs)
测试用例:
print(str_to_timedelta("4w 2d 5h")) # 输出: 30 days, 5:00:00 print(str_to_timedelta("1w")) # 输出: 7 days, 0:00:00 print(str_to_timedelta("3w 1d 5h 3m")) # 输出: 22 days, 5:03:00
方法二:拆分字符串+字典映射(无正则)
若对正则不熟悉,可拆分字符串后通过字典处理,逻辑直观易懂:
from datetime import timedelta def str_to_timedelta(duration_str): # 定义单位对应的数值转换逻辑 unit_handler = { 'w': lambda x: x * 7, 'd': lambda x: x, 'h': lambda x: x, 'm': lambda x: x } delta_args = {'days': 0, 'hours': 0, 'minutes': 0} for part in duration_str.split(): num = int(part[:-1]) unit = part[-1] if unit in ('w', 'd'): delta_args['days'] += unit_handler[unit](num) elif unit == 'h': delta_args['hours'] += unit_handler[unit](num) elif unit == 'm': delta_args['minutes'] += unit_handler[unit](num) return timedelta(**delta_args)
这两种方法的优势:
- 代码结构清晰,维护成本低,新增单位(如秒
s)只需在字典中添加对应规则 - 避免重复判断逻辑,执行效率优于逐个if分支判断
内容的提问来源于stack exchange,提问作者Roman
相关产品推荐
相关产品推荐

