【问题标题】:SQLite storing default timestamp as unixepochSQLite 将默认时间戳存储为 unixepoch
【发布时间】:2012-07-19 08:10:42
【问题描述】:

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

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 时间戳吗?

【问题讨论】:

  • AUTOINCREMENT 对于INTEGER PRIMARY KEY 不是必需的。

标签: sqlite timestamp


【解决方案1】:

注意“时间戳”不是 SQLite 已知的数据类型(参见列表 here)。 strftime() 生成的默认值实际上将存储为文本。

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

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

【讨论】:

    【解决方案2】:

    使用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

    如果列的默认值是括号中的表达式,则表达式会针对插入的每一行计算一次,并将结果用于新行。

    【讨论】:

      【解决方案3】:

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

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

      给你:

      1454521888

      'timestamp' 表列甚至可以是文本字段,使用current_timestamp 作为默认值。

      没有strftime:

      SELECT timestamp FROM ... ;
      

      给你:

      2016-02-03 17:51:28

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-01
        • 2021-01-16
        • 1970-01-01
        • 2016-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多