英文:
From UnixNano() to Time{}
问题
我想将一个 UnixNano() int64 时间戳转换回 time.Time{}。
退一步说,这是一个更大的问题。
我们有一个带有时间戳的数据库,我们使用这些时间戳来提取条目。在纳秒时间中,不应该有重复的时间戳。数据库是一个嵌入式的SQLite3数据库(通过“github.com/mattn/go-sqlite3”驱动程序),时间戳保存在一个INTEGER列中。我们对数字值进行一些排序和过滤,形式是在选择和几个视图中的子句中。
因此,当我们将整数绑定到准备好的语句中时,如:
INSERT INTO "event" ("timestamp", "command", "data") VALUES (?, ?, ?)
我们绑定的是 time.Now().UnixNano()。
然而,当我尝试将该项转换为数据结构时,我发现我无法准确地将 UnixNano 时间重新构建为 time.Time{} 结构。
它们从来都不匹配。
我应该如何做到这一点?
英文:
I want to convert a UnixNano() int64 time stamp back to a time.Time{}.
Taking a step back, here is the larger issue.
We have a database with timestamps, we use these timestamps to pull entries. In nanotime there should never be duplicate timestamps. The database is an embedded SQLite3 database (via the "github.com/mattn/go-sqlite3" driver) with the stamp held in an INTEGER column. We do some sorting and filtering with the number value, in the form of clauses on selects and within a few views.
Thus when we bind our integers to our prepared statements like:
INSERT INTO "event" ("timestamp", "command", "data") VALUES (?, ?, ?)
we bind time.Now().UnixNano().
However when I try to convert the item to a data structure, I find I cannot accurately take a UnixNano time and reconstitute it back to a time.Time{} structure.
They never match.
How should I do this?
答案1
得分: 32
t1 := time.Now()
fmt.Println(t1, t1.UnixNano())
t2 := time.Unix(0, t1.UnixNano())
fmt.Println(t2, t2.UnixNano())
输出结果为:
2009-11-10 23:00:00 +0000 UTC 1257894000000000000
2009-11-10 23:00:00 +0000 UTC 1257894000000000000
http://play.golang.org/p/Q68IaR9zPK
顺便问一下,你确定保存到数据库的整数值没有被截断吗(例如,可以存储int64类型的值)?
英文:
t1 := time.Now()
fmt.Println(t1, t1.UnixNano())
t2 := time.Unix(0, t1.UnixNano())
fmt.Println(t2, t2.UnixNano())
gives you
2009-11-10 23:00:00 +0000 UTC 1257894000000000000
2009-11-10 23:00:00 +0000 UTC 1257894000000000000
http://play.golang.org/p/Q68IaR9zPK
BTW, are you sure that the integer value saved to the database is not truncated (e.g. can store int64)?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论