英文:
TimeZone string formatting
问题
你好!以下是将这段代码从Python翻译成Go的方法:
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now().UTC().Format("-0700"))
}
在Go中,time.Now().UTC()
可以替代Python中的gmtime.gmtime()
,它返回当前的UTC时间。然后,使用Format()
函数将时间格式化为-0700
的形式。
希望对你有帮助!如果你有任何其他问题,请随时问我。
英文:
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?
答案1
得分: 2
你不需要在那里调用Local()
,因为time.Now()
返回的是本地时间。当我在我的机器上运行你的代码时,我得到了正确的结果。看起来你运行代码的时区是UTC。(你可以通过打印time.Now().Zone()
的结果来查看时区)。
Python中的gmtime
返回的是UTC时间。在Go中,你可以通过在时间值上调用In(time.UTC)
将时间转换为UTC。(我不是Python专家,也不知道为什么gmtime()
的时区被报告为本地时区(我在我的机器上重现了这个问题)。)
英文:
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).)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论