In Go lang, how to get the epoch timestamp, the number of seconds passed since the epoch? If you would convert a time string to epoch timestamp, you can first parse the time string and then use the Unix() function to convert it into an epoch timestamp as follows.
You can use time. Now(). UTC() if you'd rather have UTC than your local time zone.
1656892805 seconds elapsed since jan 1 1970. Unix time (also known as POSIX time or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus leap seconds.
The Time. Unix() function in Go language is used to yield “t” as a Unix time that is the number of seconds passed from January 1, 1970, in UTC and the output here doesn't rely upon the location connected with t. Moreover, this function is defined under the time package.
import "time"
...
port[5] = time.Now().Unix()
If you want it as string
just convert it via strconv
:
package main
import (
"fmt"
"strconv"
"time"
)
func main() {
timestamp := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
fmt.Println(timestamp) // prints: 1436773875771421417
}
Another tip. time.Now().UnixNano()
(godoc) will give you nanoseconds since the epoch. It's not strictly Unix time, but it gives you sub second precision using the same epoch, which can be handy.
Edit: Changed to match current golang api
Building on the idea from another answer here, to get a human-readable interpretation, you can use:
package main
import (
"fmt"
"time"
)
func main() {
timestamp := time.Unix(time.Now().Unix(), 0)
fmt.Printf("%v", timestamp) // prints: 2009-11-10 23:00:00 +0000 UTC
}
Try it in The Go Playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With