gpt4 book ai didi

json - 将纪元时间戳解码为 time.Time

转载 作者:数据小太阳 更新时间:2023-10-29 03:35:25 26 4
gpt4 key购买 nike

使用此结构运行 Decode() 会产生“时间戳”列错误:

type Metrics struct {
Id int `orm:"column(id);auto"`
Name string `orm:"column(name);size(255);null" json:"metric_name"`
json:"lon"`
Timestamp time.Time `orm:"column(timestamp);type(datetime)" json:"timestamp;omitempty"`

}

错误:

 parsing time "1352289160" as ""2006-01-02T15:04:05Z07:00"": cannot parse "1352289160" as """

如何将其解析为 time.Time 值?

谢谢

最佳答案

如果您可以将时间戳作为 unix 时间(我假设它是什么),只需将该字段声明为 int64,即

type Metrics struct {
...
Timestamp int64 `orm:"column(timestamp);type(datetime)" json:"timestamp;omitempty"`
}

然后您可以将其转换为 Go 的 Time 类型

var m Metrics 
...
When := time.Unix(m.Timestamp, 0)

另一种选择是为 Metrics 类型编写自定义 UnmarshalJSON 处理程序:

func (this *Metrics) UnmarshalJSON(data []byte) error {
var f interface{}
err := json.Unmarshal(data, &f)
if err != nil { return err; }
m := f.(map[string]interface{})
for k, v := range m {
switch k {
case "metric_name": this.Name = v.(string)
case "timestamp": this.Timestamp = time.Unix(int64(v.(float64)), 0)
...
}
}
}

然后你在结构中有适当的 time.Time 值,这使得使用它更容易。

关于json - 将纪元时间戳解码为 time.Time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41593301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com