Skip to main content

How to Get Unix Seconds from a time.Time in Go

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Unix time counts the seconds since 1 January 1970 UTC, and many formats store times that way. In Go, t.Unix() turns a time.Time into that number, and time.Unix(seconds, 0) turns it back.

Syntax​

Syntax
<seconds> := <t>.Unix()
<milliseconds> := <t>.UnixMilli()
<t> := time.Unix(<seconds>, <nanoseconds>)
PartWhat it does
<t>.Unix()The seconds since 1970-01-01 00:00:00 UTC, as an int64.
<t>.UnixMilli()The same moment in milliseconds.
time.Unix(<s>, <ns>)Builds a time.Time from seconds and extra nanoseconds.

The time documentation: "Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t."

The Example​

The example takes 09:30 UTC on 26 November 2026, prints it as Unix seconds and milliseconds, and turns the seconds back into a time.

Prerequisites​

  • Go. go run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which sets t to 09:30 UTC on 26 November 2026, prints t.Unix() and t.UnixMilli(), and prints time.Unix(1795685400, 0) in UTC.

main.go
package main

import (
"fmt"
"time"
)

func main() {
t := time.Date(2026, 11, 26, 9, 30, 0, 0, time.UTC)

fmt.Println(t.Unix())
fmt.Println(t.UnixMilli())
fmt.Println(time.Unix(1795685400, 0).UTC())
}

.UTC() shows the converted time in UTC; without it, Go would show it in the computer's local time zone.

Step 2: Run It​

Terminal
go run main.go
Output
1795685400
1795685400000
2026-11-26 09:30:00 +0000 UTC

A zsh terminal where go run main.go prints 1795685400, 1795685400000 and 2026-11-26 09:30:00 +0000 UTC.

The milliseconds are the seconds with three more digits. The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Using UnixMilli() where seconds are expectedThe value is 1,000 times too bigUse Unix()
Printing time.Unix(...) and reading it as UTCIt's shown in the local time zoneCall .UTC() before printing
Storing the result in an int32It overflows in 2038Keep the int64 that Unix() returns

Troubleshooting​

SymptomLikely causeFix
A date shows up thousands of years aheadMilliseconds were read as secondsDivide by 1,000, or use Unix()
A converted time is hours offIt printed in local timeAdd .UTC()

FAQ​

How do I get the current Unix time?​

time.Now().Unix().

Does the time zone change the number?​

No. As the documentation says, the result doesn't depend on the time's location: the same moment gives the same seconds everywhere.

Conclusion​

t.Unix() gives the seconds since 1970 UTC and t.UnixMilli() the milliseconds; time.Unix(seconds, 0) goes back. Call .UTC() when you print a converted time.

Additional Resources​