Skip to main content
 首页 » 编程设计

postgresql之节省时间。golang 中的时间到带有时区字段的 postgres 时间戳

2024年12月31日4powertoolsteam

我正在尝试在 golang 中测试我的数据库(即 Postgres)模型。问题是当我从数据库中检索时,具有 time.Time 类型的字段值不匹配。这是代码:

a := myStruct{aTime: time.Now().UTC(), ...} 
res, err := db.Exec("INSERT INTO my_table VALUES ($1, $2, ...) RETURNING id", a.aTime, ...) 
... 
// some logic for setting id in struct a 
... 
row := db.QueryRow("SELECT * FROM my_table WHERE id = $1", a.id) 
var test *myStruct 
row.Scan(test) 
reflect.DeepEqual(a, test) // returns False 
fmt.Printf("%v\n%v", a, test) 
// {2020-02-25 12:37:16.906605805 +0000 UTC ...} 
// {2020-02-25 12:37:16.906606 +0000 UTC ...} 

数据库中的时间字段类型为timestamp with time zone

我也尝试了以下方法:

a.aTime.Equal(test.aTime) // returns false 
a.aTime = a.aTime.Round(time.Second) 
test.aTime = test.aTime.Round(time.Second) 
a.aTime.Equal(test.aTime) // returns true 

但仍然 reflect.DeepEqual 返回 false。问题是时间字段,因为当我执行以下操作时,reflect.DeepEqual 变为 true

a.aTime = test.aTime 

有人知道如何解决这个问题吗?

请您参考如下方法:

这些时间不相等:

// {2020-02-25 12:37:16.906605805 +0000 UTC ...} 
// {2020-02-25 12:37:16.906606 +0000 UTC ...} 

DB 值具有(四舍五入的)微秒精度 - Go 的时间具有纳秒精度。

我建议在将时间添加到数据库之前四舍五入到您的数据库和您的需求所支持的精度水平,例如

a.Atime = a.aTime.Round(time.Microsecond) // round to nearest micro (per Markus comment) 
 
res, err := db.Exec("INSERT INTO my_table VALUES ($1, $2, ...) RETURNING id", a.aTime, ...) 

还要比较时间相等性,使用 time.Equal() :

Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.