Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From UnixNano() to Time{}

Tags:

sqlite

go

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?

like image 530
grmartin Avatar asked Jul 30 '15 14:07

grmartin


1 Answers

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)?

like image 133
Alex Netkachov Avatar answered Oct 25 '22 02:10

Alex Netkachov