SQLite Forum

SQL query help for between times and grouping times
Login
Here is some SQL that will validate the conversion.

```
with src1(x)
  as (
         select strftime('%Y-%m-%d %H:%M:%S', 'now')
      union all
         select strftime('%Y-%m-%d %H:%M:%S', x, '+1 hour')
           from src1
          limit 8760
     ),
     src2(x, dp, th, trest)
  as (
      select x,
             printf('%d/%d/%d', strftime('%m', x) + 0, strftime('%d', x) + 0, strftime('%Y', x) + 0),
             strftime('%H', x),
             strftime(':%M:%S', x)
        from src1
     ),
     src3(x, dp, th, trest, nh, ap)
  as (
      select x,
             dp,
             th,
             trest,
             th + iif(th between '13' and '23', -12, iif(th == '00', 12, 0)),
             iif(th between '12' and '23', 'PM', 'AM')
        from src2
     ),
     src4(x, dp, tp)
  as (
      select x,
             dp,
             nh || trest || ' ' || ap
       from src3
     ),
     cvt(x, dp, tp, y)
  as (
      select x,
             dp,
             tp,
             printf('%4d-%02d-%02d %02d:%s',
                  substr(dp, length(dp)-3, 4) + 0,
                  substr(dp, 1, instr(dp, '/') - 1) + 0,
                  trim(substr(dp, instr(dp, '/') + 1, 2), '/') + 0,
                  substr(tp, 1, instr(tp, ':') - 1) + iif(instr(tp, 'PM') > 1 and substr(tp,1,2) != '12', 12, iif(instr(tp, 'AM') > 1 and substr(tp, 1, 2) == '12', -12, 0)),
                  substr(tp, instr(tp, ':') + 1, 5))
        from src4
     )
select *, x == y
  from cvt
;
```