You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Oracle中使用REGEXP_REPLACE转换时间为hh:mm格式的查询实现

Oracle时间字符串格式标准化实现方案

原写法问题说明

  1. 字段名拼写错误:测试数据集的字段为srt_tm,原查询误写为strt_tm
  2. 替换逻辑错误:原写法将匹配到的时间字符串直接替换为固定文本hh:mm,无法得到实际时间值
  3. 缺少两个核心处理逻辑:未去除前导空格、未给单位数小时补前导零

正确实现方案

通过两层REGEXP_REPLACE分别处理前导空格和小时补零需求,逻辑清晰且适配所有测试场景:

with
  test_data (srt_tm) as (
    select '1:00'  from dual union all
    select '01:00' from dual union all
    select ' 01:00' from dual union all
    select '4:00'  from dual union all
    select '04:00' from dual union all
    select ' 04:00' from dual
  )
select 
  srt_tm as "原始时间字符串",
  REGEXP_REPLACE(REGEXP_REPLACE(srt_tm, '^\s+', ''), '^(\d):', '0\1:') as "标准化后时间(hh:mm)"
from test_data;

正则逻辑说明

  • 内层REGEXP_REPLACE(srt_tm, '^\s+', ''):匹配字符串开头的所有空白字符并替换为空,完成前导空格清理
  • 外层REGEXP_REPLACE(..., '^(\d):', '0\1:'):匹配开头仅1位数字后跟冒号的场景,\1引用捕获到的小时数值,前面补0实现小时统一为两位格式

执行结果

原始时间字符串标准化后时间(hh:mm)
1:0001:00
01:0001:00
01:0001:00
4:0004:00
04:0004:00
04:0004:00

内容的提问来源于stack exchange,提问作者Sona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:36:03