go语言中的时间转换问题

Val*_*tin 5 time go

我试图用Go语言来理解时间转换的问题.这是代码示例:

package main

import (
    "fmt"
    "time"
)

func unix2Str(ts int64) string {
    const layout = "20060102"
    t := time.Unix(ts, 0)
    return t.Format(layout)
}

func unixTime(ts string) int64 {
    const layout = "20060102"
    t, err := time.Parse(layout, ts)
    if err != nil {
            fmt.Println(err)
            return 0
    }
    return t.Unix()
}
func main() {
    ts1 := "20110320"
    ts2 := "20110321"

    ut1 := unixTime(ts1)
    ut2 := unixTime(ts2)

    fmt.Println(ts1, ut1, unix2Str(ut1))
    fmt.Println(ts2, ut2, unix2Str(ut2))
}
Run Code Online (Sandbox Code Playgroud)

它打印以下输出:

20110320 1300579200 20110319
20110321 1300665600 20110320
Run Code Online (Sandbox Code Playgroud)

但是,由于我从字符串格式转换为Unix并且反向,我希望字符串格式的日期具有相同的结果.但事实并非如此.实际上,打印的unix时间1300579200在python中转换为我开始的原始日期,例如

>>> time.strftime("%Y%m%d", time.gmtime(1300579200))
'20110320'
Run Code Online (Sandbox Code Playgroud)

这是Go代码中的错误还是我错过了什么?

pet*_*rSO 8

这是因为您的本地时区和UTC之间的差异.Parse返回UTC时间并Unix返回当地时间.例如,

package main

import (
    "fmt"
    "time"
)

func unix2Str(ts int64) string {
    const layout = "20060102"
    t := time.Unix(ts, 0)
    fmt.Println(t)
    return t.Format(layout)
}

func unixTime(ts string) int64 {
    const layout = "20060102"
    t, err := time.Parse(layout, ts)
    if err != nil {
        fmt.Println(err)
        return 0
    }
    fmt.Println(t)
    return t.Unix()
}

func main() {
    ts1 := "20110320"
    ts2 := "20110321"

    ut1 := unixTime(ts1)
    ut2 := unixTime(ts2)

    fmt.Println(ts1, ut1, unix2Str(ut1))
    fmt.Println(ts2, ut2, unix2Str(ut2))
}
Run Code Online (Sandbox Code Playgroud)

输出:

2011-03-20 00:00:00 +0000 UTC
2011-03-21 00:00:00 +0000 UTC
2011-03-19 20:00:00 -0400 EDT
20110320 1300579200 20110319
2011-03-20 20:00:00 -0400 EDT
20110321 1300665600 20110320
Run Code Online (Sandbox Code Playgroud)

func Parse

func Parse(layout, value string) (Time, error)
Run Code Online (Sandbox Code Playgroud)

Parse解析格式化的字符串并返回它表示的时间值.布局通过显示定义的参考时间来定义格式

Mon Jan 2 15:04:05 -0700 MST 2006
Run Code Online (Sandbox Code Playgroud)

会被解释,如果它是价值; 它作为输入格式的一个例子.然后对输入字符串进行相同的解释.

在没有时区指示符的情况下,Parse返回UTC时间.


功能Unix

func Unix(sec int64, nsec int64) Time
Run Code Online (Sandbox Code Playgroud)

Unix返回与自1970年1月1日UTC以来给定的Unix时间,秒秒和nsec纳秒相对应的本地时间.