Unix timestamps in Go

Go's time.Time converts to and from Unix time in every unit. The parts that surprise people are the reference-date layout strings and the zone a parsed time ends up in.

Current timestamp

now := time.Now()
fmt.Println(now.Unix())        // e.g. 1763164800           seconds
fmt.Println(now.UnixMilli())   // e.g. 1763164800123        milliseconds (Go 1.17+)
fmt.Println(now.UnixMicro())   // e.g. 1763164800123456     microseconds (Go 1.17+)
fmt.Println(now.UnixNano())    // e.g. 1763164800123456789  nanoseconds

All four return int64.

Timestamp to time

Every example uses 1700000000, which is 14 November 2023 at 22:13:20 UTC, so you can compare the output across languages or check it in the timestamp converter.

t := time.Unix(1700000000, 0)                    // seconds, nanoseconds
fmt.Println(t.UTC().Format(time.RFC3339))        // 2023-11-14T22:13:20Z
fmt.Println(time.UnixMilli(1700000000123).UTC()) // 2023-11-14 22:13:20.123 +0000 UTC

loc, err := time.LoadLocation("America/New_York")
if err != nil {
	log.Fatal(err)
}
fmt.Println(t.In(loc).Format("2006-01-02 15:04:05 MST"))   // 2023-11-14 17:13:20 EST

time.Unix returns a time in the local zone of the machine. The instant is right, but it prints in local time until you call .UTC() or .In(loc).

Time to timestamp

t, err := time.Parse(time.RFC3339, "2023-11-14T22:13:20Z")
if err != nil {
	log.Fatal(err)
}
fmt.Println(t.Unix())   // 1700000000

fmt.Println(time.Date(2023, time.November, 14, 22, 13, 20, 0, time.UTC).Unix())   // 1700000000

t2, _ := time.ParseInLocation("2006-01-02 15:04:05", "2023-11-14 17:13:20", loc)
fmt.Println(t2.Unix())  // 1700000000

Pitfalls

  • Layouts are an example, not a pattern. Go formats and parses by showing how the reference time Mon Jan 2 15:04:05 MST 2006 would look. "2006-01-02" is year-month-day; "2006-02-01" silently swaps month and day.
  • time.Parse with no zone in the input returns UTC, not local time. Use time.ParseInLocation when the string is in a known zone.
  • LoadLocation needs the zone database. Minimal containers often lack it. Import time/tzdata (Go 1.15 and later) to embed a copy in the binary.
  • UnixNano has a limited range. An int64 of nanoseconds only covers 1678 to 2262; outside that the result is undefined.
  • Compare instants with t.Equal(u), not ==, which also compares the location.

Questions

How do I get a Unix timestamp in milliseconds in Go?

time.Now().UnixMilli(), available since Go 1.17. On older versions use time.Now().UnixNano() / int64(time.Millisecond).

How do I convert a Unix timestamp to a string in Go?

time.Unix(ts, 0).UTC().Format(time.RFC3339) gives an ISO 8601 string such as 2023-11-14T22:13:20Z.

Why does time.Unix() print a different hour from what I expect?

time.Unix returns the time in the machine's local zone. Call .UTC() or .In(location) before formatting. The underlying instant is the same either way.