时区字符串格式化

huangapple go评论68阅读模式
英文:

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).)

huangapple
  • 本文由 发表于 2016年12月25日 04:22:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41316596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定