自golang纳秒时间戳以来的时间

Q1. How do I create a golang time struct from a nanosecond timestamp?

Q2. How do I then compute the number of hours since this timestamp?

In Go a "time" object is represented by a value of the struct type time.Time.

You can create a Time from a nanosecond timestamp using the time.Unix(sec int64, nsec int64) function where it is valid to pass nsec outside the range [0, 999999999].

And you can use the time.Since(t Time) function which returns the elapsed time since the specified time as a time.Duration (which is basically the time difference in nanoseconds).

t := time.Unix(0, yourTimestamp)
elapsed := time.Since(t)

To get the elapsed time in hours, simply use the Duration.Hours() method which returns the duration in hours as a floating point number:

fmt.Printf("Elapsed time: %.2f hours", elapsed.Hours())

Try it on the Go Playground.

Note:

Duration can format itself intelligently in a format like "72h3m0.5s", implemented in its String() method:

fmt.Printf("Elapsed time: %s", elapsed)

You pass the nanoseconds to time.Unix(0, ts), example:

func main() {
    now := time.Now()
    ts := int64(1257856852039812612)
    timeFromTS := time.Unix(0, ts)
    diff := now.Sub(timeFromTS)
    fmt.Printf("now: %v
time from ts: %v
diff: %v
diff int:", now, timeFromTS, diff, int64(diff))
}

playground