英文:
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"`
Lon float64 `orm:"column(lon);null" json:"lon"`
Timestamp time.Time `orm:"column(timestamp);type(datetime)" json:"timestamp,omitempty"`
}
错误信息:
将时间“1352289160”解析为“2006-01-02T15:04:05Z07:00”时出错:无法将“1352289160”解析为“”
如何将其解析为time.Time值?
谢谢
英文:
Running Decode() with this struct produces an error with the 'timestamp' column:
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"`
}
The error:
parsing time "1352289160" as ""2006-01-02T15:04:05Z07:00"": cannot parse "1352289160" as """
How can I parse it into a time.Time value?
Thank you
答案1
得分: 5
如果你愿意将时间戳作为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值,这样处理起来更方便。
英文:
If you're okay to have the timestamp as unix time (I assume that what it is) just declare the field as int64
, ie
type Metrics struct {
...
Timestamp int64 `orm:"column(timestamp);type(datetime)" json:"timestamp;omitempty"`
}
You can then convert it to Go's Time
type with
var m Metrics
...
When := time.Unix(m.Timestamp, 0)
Another option is to write custom UnmarshalJSON
handler for the Metrics type:
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)
...
}
}
}
Then you have proper time.Time value in struct which makes working with it easier.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论