golang连接mysql时一般会加上loc=Local参数,否则timestamp字段储存和读取时间会有偏差,我们来看看为什么
timestamp原理
timestamp储存的是距离1970-01-01 00:00:00的秒数差,timestamp并不保存时区信息
准备表
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ts` timestamp(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 ROW_FORMAT = Dynamic;
写入
insert into test(ts) values("2022-09-11 08:00:00");
插入上面数据时,数据库会将"2022-09-11 08:00:00"(北京时间)时间转成UTC时间"2022-09-11 00:00:00",再转成时间戳1662854400存入
select unix_timestamp(ts) from test;//返回1662854400
有些同学好奇了,数据库怎么知道"2022-09-11 08:00:00"这个时间是北京时间,原因是时区
SELECT @@GLOBAL.time_zone, @@SESSION.time_zone;//返回SYSTEM SYSTEM
global.time_zone: mysql服务设置的时区
session.time_zone: 此次连接的设置时区,一般就是global.time_zone,上面返回的SYSTEM,代表取系统时区,也就是东八区
Values for TIMESTAMP columns are converted from the session time zone to UTC for storage, and from UTC to the session time zone for retrieval.
value:"2022-09-11 08:00:00" session.time_zone:"东八区" => UTC "2022-09-11 00:00:00"=>1662854400
golang timestamp插入
有些同学可能以为连接参数loc=Local就是设置session.time_zone,没设置就会时区对不上,所以有问题,我们测试下
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:xxx@tcp(127.0.0.1:3306)/test?parseTime=true")
if err != nil {
panic(err)
}
defer db.Close()
var gZone, sZone string
err = db.QueryRow("SELECT @@GLOBAL.time_zone, @@SESSION.time_zone").Scan(&gZone, &sZone)
if err != nil {
panic(err)
}
fmt.Println(gZone, sZone) //打印SYSTEM SYSTEM
}
可以看出,未设置loc=Local并不影响session.time_zone,它的值还是系统时区东八区
插入time.Time
清空数据,我们插入一条time.Time类型数据
db.Exec(`insert into test(ts) values (?)`, time.Now()) //北京时间2022-09-11 22:17:07
查下数据库数据
mysql> select ts,unix_timestamp(ts) from test;
+---------------------+--------------------+
| ts | unix_timestamp(ts) |
+---------------------+--------------------+
| 2022-09-11 14:17:07 | 1662877027 |
+---------------------+--------------------+
1 row in set (0.01 sec)
插入的是当前时间22:17:07,展示的却是14:17:07,我们再看比较下时间戳,北京时间2022-09-11 22:17:07的时间戳应为1662905827,但实际储存的是1662877027
(1662905827-1662877027)/3600 = 8//差了8小时
结论: 当未设置loc=Local时,timestamp储存time.Time确实有偏差
插入时间字符串
清空数据,我们插入一条时间字符串类型数据
db.Exec(`insert into test(ts) values (?)`, “2022-09-11 22:17:07”) //北京时间2022-09-11 22:17:07
查下数据库数据
mysql> select ts,unix_timestamp(ts) from test;
+---------------------+--------------------+
| ts | unix_timestamp(ts) |
+---------------------+--------------------+
| 2022-09-11 22:17:07 | 1662905827 |
+---------------------+--------------------+
1 row in set (0.02 sec)
时间字符串插入后数据没有偏差,是正确的
综上,只有向timestamp字段插入time.Time数据时,会有时间偏差
原因
还是看golang mysql库源码,mysql库的配置中有
func NewConfig() *Config {
return &Config{
Collation: defaultCollation,
Loc: time.UTC,
MaxAllowedPacket: defaultMaxAllowedPacket,
AllowNativePasswords: true,
}
}
未设置loc=Local时,Loc=time.UTC,当传入的参数是time.Time时:
case time.Time:
...
v := v.In(mc.cfg.Loc)
v = v.Add(time.Nanosecond * 500) // To round under microsecond
year := v.Year()
year100 := year / 100
year1 := year % 100
month := v.Month()
day := v.Day()
hour := v.Hour() //当强制时区变换后,此Hour值会不同
minute := v.Minute()
second := v.Second()
micro := v.Nanosecond() / 1000
...
强制时区变换,变换后的v.Hour()=14,测试代码如下
t := time.Unix(1662905827, 0) //北京时间2022-09-11 22:17:07
utc := t.In(time.UTC)
fmt.Println(t.Hour(), ":", t.Minute(), ":", t.Second()) //打印 22:17:7
fmt.Println(utc.Hour(), ":", utc.Minute(), ":", utc.Second())//打印 14:17:7
分析
db.Exec(`insert into test(ts) values (?)`, time.Now()) //北京时间2022-09-11 22:17:07
value:"2022-09-11 14:17:07" session.time_zone:"东八区" => UTC "2022-09-11 06:17:07"=>1662877027
db.Exec(`insert into test(ts) values (?)`, “2022-09-11 22:17:07”) //北京时间2022-09-11 22:17:07
value:"2022-09-11 22:17:07" session.time_zone:"东八区" => UTC "2022-09-11 14:17:07"=>1662905827