How can I translate this code from Python to Go?
>>> from time import gmtime
>>> from time import strftime
>>> strftime("%z", gmtime())
'-0800'
I tried:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now().Local().Format("-0700"))
}
But it's obviously not working:
+0000
I am somewhat confused in general about the formatting part of time because the const symbols (e.g. stdNumTZ
) are not exported from the time
package.
Is time.Now().Local()
in Go the real substitute for gmtime.gmtime()
in Python?
You don't need to call Local()
there since time.Now()
returns local time. When I try to run your code on my machine, I get the correct result. It looks like the time zone where you're running this is UTC. (You can see the time zone by printing the result of time.Now().Zone()
).
gmtime
in Python returns UTC time. In Go, you can convert a time to UTC by calling In(time.UTC)
on the time value. (I'm not a Python expert, and I don't know why the time zone of gmtime()
is reported as the local time zone (I reproduced that on my machine).)