在sqlite中将12小时转换为24小时时间格式

时间:2013-12-18 10:03:25

标签: datetime sqlite format

假设我有一个名为'importscript.sql'的脚本来创建一个表,并从名为'rawdata.txt'的文本文件中填充它,如下所示:

    CREATE TABLE rawdata (
    timestamp text,
    value REAL
    );
    .separator ,
    .import '~/path of the file/rawdata.txt' rawdata

'rawdata.txt'文件如下所示:

4/14/2012 3:50:09 PM,24.7
4/14/2012 3:51:09 PM,24.2
4/14/2012 3:52:09 PM,99.3

然后使用以下命令创建一个名为RAWDATA.db的数据库,其中包含rawdata表:

sqlite3 RAWDATA.db < ~/path to the script/importscript.sql

导入完成后的表格如下所示:

timestamp              value    
4/14/2012 3:50:09 PM   24.7
4/14/2012 3:51:09 PM   24.2
4/14/2012 3:52:09 PM   99.3

但我希望它看起来像这样

timestamp              value
4/14/2012 15:50:09      24.7
4/14/2012 15:51:09      24.2
4/14/2012 15:52:09      99.3

如何将此时间戳列转换为24小时格式?

1 个答案:

答案 0 :(得分:4)

为了使用SQLite日期/时间函数并允许日期比较(和排序),日期应存储在YYYY-MM-DD HH:MM-SS

所以,我的回答将解决您的问题和日期转换:

UPDATE rawdata SET timestamp=(SELECT DATETIME(SUBSTR(timestamp, s2+1, 4)||'-01-01',
  SUBSTR(timestamp,    1, s1   -1)||' months', '-1 months',
  SUBSTR(timestamp, s1+1, s2-s1-1)||' days', '-1 days',
  SUBSTR(timestamp, s3+1, s4-s3-1)||' hours',
  SUBSTR(timestamp, s4+1, s5-s4-1)||' minutes',
  SUBSTR(timestamp, s5+1, s6-s5-1)||' seconds',
  CASE WHEN SUBSTR(timestamp, s3+1, s4-s3-1) = '12' THEN '-12 hours' ELSE '0 hours' END,
  CASE WHEN SUBSTR(timestamp, s6+1) LIKE 'PM' THEN '+12 hours' ELSE '0 hours' END
)
FROM (
  SELECT *,
    INSTR(SUBSTR(timestamp, s1+1), '/')+s1 AS s2,
    INSTR(SUBSTR(timestamp, s4+1), ':')+s4 AS s5,
    INSTR(SUBSTR(timestamp, s3+1), ' ')+s3 AS s6
  FROM (
    SELECT timestamp,
      INSTR(timestamp, '/') AS s1, 
      INSTR(timestamp, ' ') AS s3, 
      INSTR(timestamp, ':') AS s4
  )
));

这个可怕的块获取所有分隔符位置,从组件重建日期并处理PM。请注意1...11AM => +01...11PM => +12,但12AM => -1212PM => +0

SQL Fiddle中查看。