Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining a Unix Timestamp in Go Language (current time in seconds since epoch)

Tags:

timestamp

unix

go

People also ask

What is the syntax to get the epoch timestamp in go?

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.

How do I get the timestamp on go?

You can use time. Now(). UTC() if you'd rather have UTC than your local time zone.

How many seconds have passed since the Unix epoch?

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.

What is Unix time in Golang?

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.