将纪元时间戳解组为 time.Time
Unmarshaling epoch timestamp into time.Time
运行 使用此结构的 Decode() 在 'timestamp' 列中产生错误:
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)
另一种选择是为指标类型编写自定义 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 值,这使得使用它更容易。
运行 使用此结构的 Decode() 在 'timestamp' 列中产生错误:
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)
另一种选择是为指标类型编写自定义 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 值,这使得使用它更容易。