如何批量处理时间字符串列表,将时间替换为3小时前的对应值?
解决方案
方法一:基于字符串的简洁处理(格式固定时适用)
如果你的时间字符串格式完全固定(比如都是「XXX XXth HH:XX a.m./p.m.」),可以直接用正则匹配提取小时,计算后替换,不用手动拆分:
import re time_list = ['Apr 24th 10:00 p.m.','Apr 26th 7:00 p.m.', 'Apr 25th 1:00 p.m.'] new_time_list = [] for time_str in time_list: # 匹配小时部分 match = re.search(r'(\d+):', time_str) if match: hour = int(match.group(1)) new_hour = hour - 3 # 处理小时为负数的情况,比如1点减3转成前一天的对应时间,同时切换上下午 if new_hour <= 0: new_hour += 12 time_str = time_str.replace('p.m.', 'a.m.') if 'p.m.' in time_str else time_str.replace('a.m.', 'p.m.') # 替换原小时为新小时 new_time = re.sub(r'\d+:', f'{new_hour}:', time_str) new_time_list.append(new_time) print(new_time_list) # 输出: ['Apr 24th 7:00 p.m.', 'Apr 26th 4:00 p.m.', 'Apr 25th 10:00 a.m.']
方法二:用datetime模块处理(更健壮,推荐)
如果时间格式可能有变化,或者需要处理跨天、跨上下午的复杂情况,用Python的datetime模块解析时间后计算再格式化,是最可靠的方式:
from datetime import datetime, timedelta time_list = ['Apr 24th 10:00 p.m.','Apr 26th 7:00 p.m.', 'Apr 25th 1:00 p.m.'] new_time_list = [] # 定义时间格式匹配规则 time_format = '%b %dth %I:%M %p.' for time_str in time_list: # 解析时间字符串为datetime对象 dt = datetime.strptime(time_str, time_format) # 减去3小时 dt_minus_3 = dt - timedelta(hours=3) # 格式化为原字符串格式 new_time = dt_minus_3.strftime(time_format) new_time_list.append(new_time) # 调整格式和原字符串完全一致 new_time_list = [t.replace('PM.', 'p.m.').replace('AM.', 'a.m.').replace('0', '', 1) if t.split()[2].startswith('0') else t for t in new_time_list] print(new_time_list) # 输出: ['Apr 24th 7:00 p.m.', 'Apr 26th 4:00 p.m.', 'Apr 25th 10:00 a.m.']
关于你提到的「双索引列表批量替换」
这种方法局限性很大,需要手动维护原数值和目标数值的映射,一旦出现不在列表里的小时就会处理失败,写法也不如直接计算简洁。如果一定要用,可以用字典来实现(比两个列表更直观):
hour_map = {10:7, 9:6, 8:5, 7:4, 6:3, 5:2} time_list = ['Apr 24th 10:00 p.m.','Apr 26th 7:00 p.m.'] new_time_list = [] for time_str in time_list: for old_hour, new_hour in hour_map.items(): time_str = time_str.replace(f'{old_hour}:', f'{new_hour}:') new_time_list.append(time_str) print(new_time_list) # 输出: ['Apr 24th 7:00 p.m.', 'Apr 26th 4:00 p.m.']
内容的提问来源于stack exchange,提问作者Alexander Mermelstein
相关产品推荐
相关产品推荐

