211

是否可以在 sqlite 数据库中创建一个具有默认为的时间戳列的表DATETIME('now')

像这样:

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t TIMESTAMP DEFAULT DATETIME('now')
);

这给出了一个错误......如何解决?

4

8 回答 8

322

我相信你可以使用

CREATE TABLE test (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  t TIMESTAMP
  DEFAULT CURRENT_TIMESTAMP
);

从 3.1 版开始(来源

于 2008-10-14T08:01:44.233 回答
107

根据博士。hipp 在最近的列表帖子中:

CREATE TABLE whatever(
     ....
     timestamp DATE DEFAULT (datetime('now','localtime')),
     ...
);
于 2008-10-23T00:44:24.457 回答
56

这只是一个语法错误,你需要括号:(DATETIME('now'))

如果您查看文档,您会注意到在语法中的 'expr' 选项周围添加的括号。

于 2009-04-15T22:47:15.980 回答
25

这是基于问题的其他答案和评论的完整示例。在示例中,时间戳 ( created_at-column) 保存为unix epoch UTC 时区,仅在必要时转换为本地时区。

使用 unix epoch 可以节省存储空间 - 当存储为 ISO8601 字符串时,4 字节整数与 24 字节字符串,请参阅datatypes。如果 4 字节不够,可以增加到 6 或 8 字节。

在 UTC 时区保存时间戳可以方便地在多个时区显示合理的值。

SQLite 版本是 3.8.6,随 Ubuntu LTS 14.04 一起提供。

$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on

create table if not exists example (
   id integer primary key autoincrement
  ,data text not null unique
  ,created_at integer(4) not null default (strftime('%s','now'))
);

insert into example(data) values
 ('foo')
,('bar')
;

select
 id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;

id|data|epoch     |utc                |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02

本地时间是正确的,因为我在查询时位于 UTC+2 DST。

于 2014-09-30T17:52:54.047 回答
10

最好使用 REAL 类型,以节省存储空间。

引用SQLite 版本 3中数据类型的 1.2 部分

SQLite 没有为存储日期和/或时间预留存储类。相反,SQLite 的内置日期和时间函数能够将日期和时间存储为 TEXT、REAL 或 INTEGER 值

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t REAL DEFAULT (datetime('now', 'localtime'))
);

请参阅列约束

插入一行而不提供任何值。

INSERT INTO "test" DEFAULT VALUES;
于 2013-11-21T12:59:04.550 回答
5

这是语法错误,因为您没有写括号

如果你写

选择 datetime('now') 然后它会给你 UTC 时间,但如果你写它查询,那么你必须在此之前添加括号所以 (datetime('now')) 为 UTC 时间。本地时间相同 Select datetime('now','localtime') 进行查询

(日期时间('现在','本地时间'))

于 2013-04-26T06:50:56.247 回答
5

如果你想要毫秒精度,试试这个:

CREATE TABLE my_table (
    timestamp DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);

不过,这会将时间戳保存为文本。

于 2021-02-18T16:00:40.090 回答
2

此替代示例将本地时间存储为整数以保存 20 个字节。该工作在字段默认值、更新触发器和视图中完成。strftime 必须使用 '%s' (单引号),因为 "%s" (双引号)对我抛出了一个 'Not Constant' 错误。

Create Table Demo (
   idDemo    Integer    Not Null Primary Key AutoIncrement
  ,DemoValue Text       Not Null Unique
  ,DatTimIns Integer(4) Not Null Default (strftime('%s', DateTime('Now', 'localtime'))) -- get Now/UTC, convert to local, convert to string/Unix Time, store as Integer(4)
  ,DatTimUpd Integer(4)     Null
);

Create Trigger trgDemoUpd After Update On Demo Begin
  Update Demo Set
    DatTimUpd  =                          strftime('%s', DateTime('Now', 'localtime'))  -- same as DatTimIns
  Where idDemo = new.idDemo;
End;

Create View If Not Exists vewDemo As Select -- convert Unix-Times to DateTimes so not every single query needs to do so
   idDemo
  ,DemoValue
  ,DateTime(DatTimIns, 'unixepoch') As DatTimIns -- convert Integer(4) (treating it as Unix-Time)
  ,DateTime(DatTimUpd, 'unixepoch') As DatTimUpd --   to YYYY-MM-DD HH:MM:SS
From Demo;

Insert Into Demo (DemoValue) Values ('One');                      -- activate the field Default
-- WAIT a few seconds --    
Insert Into Demo (DemoValue) Values ('Two');                      -- same thing but with
Insert Into Demo (DemoValue) Values ('Thr');                      --   later time values

Update Demo Set DemoValue = DemoValue || ' Upd' Where idDemo = 1; -- activate the Update-trigger

Select * From    Demo;                                            -- display raw audit values
idDemo  DemoValue  DatTimIns   DatTimUpd
------  ---------  ----------  ----------
1       One Upd    1560024902  1560024944
2       Two        1560024944
3       Thr        1560024944

Select * From vewDemo;                                            -- display automatic audit values
idDemo  DemoValue  DatTimIns            DatTimUpd
------  ---------  -------------------  -------------------
1       One Upd    2019-06-08 20:15:02  2019-06-08 20:15:44
2       Two        2019-06-08 20:15:44
3       Thr        2019-06-08 20:15:44
于 2019-06-09T00:14:14.700 回答