SQLite将默认时间戳存储为unixepoch

时间:2012-07-19 08:10:43

标签: sqlite timestamp

定义关系时,我想将属性更新为插入时的时间戳。例如,我现在有一张工作台

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

这是在更新插入时的时间戳,例如,insert into t1 (txt) values ('hello')添加行1|2012-07-19 08:07:20|hello|。但是,我希望这个日期格式化为unixepoch格式。

我读了docs,但目前尚不清楚。例如,我将表关系修改为time TIMESTAMP DEFAULT DATETIME('now','unixepoch')但我收到错误。在这里,与文档一样,now是我的时间字符串,unixepoch是修饰符,但它不起作用。有人可以帮助我如何将其格式化为unixepoch时间戳吗?

3 个答案:

答案 0 :(得分:45)

使用strftime

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

CREATE TABLE中使用它:

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

请参阅https://www.sqlite.org/lang_createtable.html#tablecoldef

  

如果列的默认值是括号中的表达式,则对于插入的每一行以及新行中使用的结果,将对表达式求值一次。

答案 1 :(得分:14)

注意'timestamp'不是SQLite已知的数据类型(参见列表here)。 strftime()生成的默认值实际上将存储为Text。

如果将值存储为数字而不是字符串很重要,请将该字段声明为整数并将CAST()添加到混合中,如下所示:

create table t1(
...
ts_field integer(4) default (cast(strftime('%s','now') as int)),
...
);

答案 2 :(得分:3)

确实是strftime,也可以这样使用:

SELECT strftime('%s', timestamp) as timestamp FROM ... ;

给你:

  

1454521888

'时间戳' table列甚至可以是文本字段,使用current_timestamp作为DEFAULT。

没有strftime:

SELECT timestamp FROM ... ;

给你:

  

2016-02-03 17:51:28

相关问题