わさっきhb

大学(教育研究)とか ,親馬鹿とか,和歌山とか,とか,とか.

SQLiteでの時刻の扱い

sqlite3コマンドにいろいろなパラメータを与えて実行し,時刻の扱いを調べてみました.

$ sqlite3 a.db "create table sample(id integer primary key, name text, time datetime)"

$ sqlite3 a.db "insert into sample(id, name, time) values (100, 'morning', datetime('now'))"

$ sqlite3 -header a.db "select * from sample"
id|name|time
100|morning|2017-05-21 20:52:42

$ sqlite3 a.db "select cast(time as integer) from sample"
2017

$ sqlite3 -header a.db "select cast(time as integer) from sample"
cast(time as integer)
2017

$ sqlite3 -header a.db "select cast(time as integer) as ctime from sample"
ctime
2017

$ sqlite3 a.db "select cast(time as real) as ctime from sample"
2017.0

$ sqlite3 a.db "select cast(time as text) as ctime from sample"
2017-05-21 20:52:42

$ sqlite3 a.db "select cast(time as none) as ctime from sample"
2017

$ sqlite3 a.db "select strftime('%s',time) as ctime from sample"
1495399962

$ ruby -e "puts Time.at(1495399962)"
2017-05-22 05:52:42 +0900

分かったこと:

  • CREATE TABLE文で,データ型としてDATETIME型を指定できる.
  • 現在時刻を得るには「datetime('now')」と書けばよい.
  • DATETIME型の値を整数値または実数値としてキャストすると,年のみになる.
  • UNIX時間(1970年1月1日からの経過秒)を得るには,「strftime('%s',DATETIME型の値)」と書けばよい.

ここまで,授業の下準備でした.実際の授業では,いくつかのテーブルに「created_at DATETIME」と「updated_at DATETIME」をつけておき,初期データのINSERT文では,時刻を'2017-05-22 05:52:42'のような定数として指定しました.
参考にさせてもらったところ: