问题
Say I have a script named 'importscript.sql' to create a table and populate it from a text file named 'rawdata.txt' like so:
CREATE TABLE rawdata (
timestamp text,
value REAL
);
.separator ,
.import '~/path of the file/rawdata.txt' rawdata
The 'rawdata.txt' file looks like this:
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
Then creating a database named RAWDATA.db with the rawdata table in it in the command prompt using:
sqlite3 RAWDATA.db < ~/path to the script/importscript.sql
The table when the import is complete will look like this:
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
But I want it to look like this
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
How do I convert this timestamp column into a 24 hour format?
回答1:
In order to make use of SQLite date/time functions and allow date comparisons (and sorting), date should be stored in YYYY-MM-DD HH:MM-SS.
So, my answer will address your question and this date conversion:
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
)
));
This horrible block get all separators position, reconstruct date from components and handle PM. Note that 1...11AM => +0 and 1...11PM => +12, but 12AM => -12 and 12PM => +0!
Check it in SQL Fiddle.
来源:https://stackoverflow.com/questions/20655003/converting-12-hour-to-24-hour-time-format-in-sqlite