如何从‘5 hours ago’这类相对时间字符串中获取绝对时间?
相对时间转绝对时间实现方案
以下是Python环境下的实现代码,可直接匹配你给出的输入格式生成预期的绝对时间列表:
from datetime import datetime, timedelta # 你的输入数据集 date = ['5 minutes ago ', '5 hours ago ', '6 seconds ago '] abs_time = [] # 时间单位映射,支持秒/分钟/小时,可按需扩展天、周等单位 unit_mapping = { 'second': 'seconds', 'seconds': 'seconds', 'minute': 'minutes', 'minutes': 'minutes', 'hour': 'hours', 'hours': 'hours' } # 获取当前时间 current_time = datetime.now() for raw_str in date: # 拆分字符串提取数值和时间单位 str_parts = raw_str.strip().split() offset = int(str_parts[0]) unit = str_parts[1] # 计算绝对时间 target_time = current_time - timedelta(**{unit_mapping[unit]: offset}) # 按需调整输出格式,示例为时分格式,如需完整时间可改为'%Y-%m-%d %H:%M:%S' abs_time.append(target_time.strftime('%H:%M')) # 输出结果 print(abs_time)
效果验证
如果当前时间为12:55,代码对5 minutes ago的输出结果为12:50,和你的预期完全一致。如需扩展支持其他时间单位,只需在unit_mapping中补充对应映射即可。
内容的提问来源于stack exchange,提问作者DevilF
相关产品推荐
相关产品推荐

