Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time since golang nanosecond timestamp

Tags:

time

go

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?

like image 436
p_mcp Avatar asked Feb 27 '15 00:02

p_mcp


People also ask

What is the type of time now () in Golang?

The Now() function in Go language is used to find the current local time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Return Value: It returns the current local time.

What does time duration do in Golang?

Duration has a base type int64. Duration represents the elapsed time between two instants as an int64 nanosecond count”. The maximum possible nanosecond representation is up to 290 years.


1 Answers

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)
like image 145
icza Avatar answered Nov 12 '22 07:11

icza