Search code examples
sqlitetimestamp

SQLite storing default timestamp as unixepoch


When defining a relation, I want to update an attribute to the timestamp at insert. For example, a working table that I have right now

CREATE TABLE t1(
id INTEGER PRIMARY KEY AUTOINCREMENT,
time TIMESTAMP
DEFAULT CURRENT_TIMESTAMP,
txt TEXT);

This is updating a timestamp on insert, for example, insert into t1 (txt) values ('hello') adds the row 1|2012-07-19 08:07:20|hello|. However, I want to have this date formatted in unixepoch format.

I read the docs but this wasn't clear. For example, I modified the table relation to time TIMESTAMP DEFAULT DATETIME('now','unixepoch') but I get an error. Here, as in the docs, now was my time string and unixepoch was the modifier but it didn't work. Could someone help me how to format it as a unixepoch timestamp?


Solution

  • Use strftime:

    sqlite> select strftime('%s', 'now');
    1342685993
    

    Use it in CREATE TABLE like this:

    sqlite> create table t1 (
       ...> id integer primary key,
       ...> time timestamp default (strftime('%s', 'now')),
       ...> txt text);
    sqlite> insert into t1 (txt) values ('foo');
    sqlite> insert into t1 (txt) values ('bar');
    sqlite> insert into t1 (txt) values ('baz');
    sqlite> select * from t1;
    1|1342686319|foo
    2|1342686321|bar
    3|1342686323|baz
    

    See https://www.sqlite.org/lang_createtable.html#tablecoldef

    If the default value of a column is an expression in parentheses, then the expression is evaluated once for each row inserted and the results used in the new row.