基于正则表达式的民用时间格式标准化替换实现问询
批量提取转换民用时间并替换回原文本
需求
检测字符串中的民用时间模式,提取所有匹配子串,按指定规则转换格式后替换回原位置。
输入文本
import re input_text = "03:00 am hay 1 Entre la 1:30 y las 2:0, o 01:02 am minuto y salimos, 19:30 pm salimos!! es importante llegar alla antes 20 :30 am, ya que 21:00 pm cierran algunos negocios, sin embargo el cine esta abierto hasta 23:30 pm o 01 : 00 am, 1:00 am 1:00 pm, : p m, 1: pm 5: pm"
正则匹配规则
用于检测目标时间模式的原型:
civil_time_pattern = r'(\d{1,2})[\s|:]*(\d{0,2})\s*(am|pm)?'
目标匹配子串
["03:00 am", "1:30", "2:0", "01:02 am", "19:30 pm", "20 :30 am", "21:00 pm", "23:30 pm", "01 : 00 am", "1:00 am", "1:00 pm", ": p m", "1: pm", "5: pm"]
时间转换规则
按照以下逻辑修正时间格式:
- 小时/分钟为空时默认设为
00 - 无am/pm标识时,根据小时自动判断:0-11为am,12-23为pm
- 有am标识时,以实际时间为准:12-23的小时自动转为pm
- 有pm标识时,标识优先:0-11的小时加12转为24小时制格式
- 小时和分钟统一补零为两位数字
- 最终格式为
HH:MM am/pm
对应的实现代码:
def convert_time(match): hh, mm, am_pm = match.groups() # 处理空值与多余空格 hh = hh.strip() if hh else "00" mm = mm.strip() if mm else "00" am_pm = am_pm.strip().lower() if am_pm else None # 处理am/pm逻辑 if not am_pm: am_pm = "am" if 0 <= int(hh) < 12 else "pm" else: if am_pm == "pm": if 0 <= int(hh) < 12: hh = str(int(hh) + 12) elif am_pm == "am": if 12 <= int(hh) < 24: am_pm = "pm" # 补零为两位格式 hh = hh.zfill(2) mm = mm.zfill(2) return f"{hh}:{mm} {am_pm}"
批量替换解决方案
使用re.sub()函数结合回调函数,自动遍历所有匹配项并完成转换替换,无需手动统计匹配次数。完整代码如下:
import re def convert_time(match): hh, mm, am_pm = match.groups() hh = hh.strip() if hh else "00" mm = mm.strip() if mm else "00" am_pm = am_pm.strip().lower() if am_pm else None if not am_pm: am_pm = "am" if 0 <= int(hh) < 12 else "pm" else: if am_pm == "pm": if 0 <= int(hh) < 12: hh = str(int(hh) + 12) elif am_pm == "am": if 12 <= int(hh) < 24: am_pm = "pm" hh = hh.zfill(2) mm = mm.zfill(2) return f"{hh}:{mm} {am_pm}" input_text = "03:00 am hay 1 Entre la 1:30 y las 2:0, o 01:02 am minuto y salimos, 19:30 pm salimos!! es importante llegar alla antes 20 :30 am, ya que 21:00 pm cierran algunos negocios, sin embargo el cine esta abierto hasta 23:30 pm o 01 : 00 am, 1:00 am 1:00 pm, : p m, 1: pm 5: pm" # 调整正则以覆盖所有目标匹配(兼容空小时/分钟的情况) civil_time_pattern = r'(\d{0,2})[\s|:]*(\d{0,2})?\s*(am|pm)?' # 执行全局替换 output_text = re.sub(civil_time_pattern, convert_time, input_text) print(output_text)
最终输出
"03:00 am hay 1 Entre la 01:30 am y las 02:00 am, o 01:02 am minuto y salimos, 19:30 pm salimos!! es importante llegar alla antes 20:30 pm, ya que 21:00 pm cierran algunos negocios, sin embargo el cine esta abierto hasta 23:30 pm o 01:00 am, 01:00 am 13:00 pm, 00:00 am, 13:00 pm 05:00 pm"
内容的提问来源于stack exchange,提问作者Matt095
相关产品推荐
相关产品推荐

