sqlite3 创建各个形式带默认时间戳的表

想创建一个每次insert数据后,默认带系统时间戳的表,逛了一圈,查到了一些相关方法。发帖记录一下。正如下图所示,除此之外还可以构建其他格式的字符串,其中有些需要注意的问题列一下。

基本样例

CREATE TABLE time(
ID INTEGER PRIMARY KEY,
CreatedTime TimeStamp NOT NULL DEFAULT CURRENT_TIMESTAMP);

建表查询得

sqlite> select * from time;
1|2021-04-28 13:35:12

然而当前系统时间为  2021-04-28 21:41:57,查阅相关文档,发现若是不对创建时间做modifier,其时间为以本初子午线的平子夜起算的平太阳时。又称格林尼治平时格林尼治时间

 

修改样例

CREATE TABLE time1(
ID INTEGER PRIMARY KEY,
CreatedTime TimeStamp NOT NULL DEFAULT (DATETIME('now','localtime')))

建表查询得

sqlite> select * from time1;
1|2021-04-28 22:00:17

此时创建查询时间正确。

参照官方文档,可以通过Time-value以及modifier进行修饰,通过修饰我们可以得到我们最终想要的时间值,例如上文中的'now'修饰符,返回UTC格式时间,'localtime'会将UTC时间转为当地时间。

the string 'now', is converted into the current date and time as obtained from the xCurrentTime method of the sqlite3_vfs object in use. The 'now' argument to date and time functions always returns exactly the same value for multiple invocations within the same sqlite3_step() call. Universal Coordinated Time (UTC) is used.

The "localtime" modifier (12) assumes the time value to its left is in Universal Coordinated Time (UTC) and adjusts that time value so that it is in localtime. If "localtime" follows a time that is not UTC, then the behavior is undefined. The "utc" modifier is the opposite of "localtime". "utc" assumes that the time value to its left is in the local timezone and adjusts that time value to be in UTC. If the time to the left is not in localtime, then the result of "utc" is undefined.

升级样例

因此按照参数关系,我们可以利用strftime()函数设计一些我们想要的样式字符串。比如如下我们就设置了时秒的单位搭配。

CREATE TABLE time2(
ID INTEGER PRIMARY KEY,
CreatedTime TimeStamp NOT NULL DEFAULT (STRFTIME('%H:%S','now','localtime')))

参考文档

https://sqlite.org/lang_datefunc.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值