14

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?

2 Answers 2

21

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)
1
  • 1
    To save some googling, max time.UnixNano() is: 2262-04-11 23:47:16.854775807 +0000 UTC
    – Highstead
    Feb 9, 2017 at 21:01
5

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\ntime from ts: %v\ndiff: %v\ndiff int:", now, timeFromTS, diff, int64(diff))
}

playground

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.