将时间戳解组为time.Time类型

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

Unmarshaling epoch timestamp into time.Time

问题

使用此结构运行Decode()会导致“timestamp”列出现错误:

  1. type Metrics struct {
  2. Id int `orm:"column(id);auto"`
  3. Name string `orm:"column(name);size(255);null" json:"metric_name"`
  4. Lon float64 `orm:"column(lon);null" json:"lon"`
  5. Timestamp time.Time `orm:"column(timestamp);type(datetime)" json:"timestamp,omitempty"`
  6. }

错误信息:

  1. 将时间“1352289160”解析为“2006-01-02T15:04:05Z07:00”时出错:无法将“1352289160”解析为“”

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

谢谢

英文:

Running Decode() with this struct produces an error with the 'timestamp' column:

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

The error:

  1. 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,例如:

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

然后,你可以使用以下代码将其转换为Go的Time类型:

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

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

  1. func (this *Metrics) UnmarshalJSON(data []byte) error {
  2. var f interface{}
  3. err := json.Unmarshal(data, &f)
  4. if err != nil { return err }
  5. m := f.(map[string]interface{})
  6. for k, v := range m {
  7. switch k {
  8. case "metric_name": this.Name = v.(string)
  9. case "timestamp": this.Timestamp = time.Unix(int64(v.(float64)), 0)
  10. ...
  11. }
  12. }
  13. }

然后,你在结构体中将获得正确的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

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

You can then convert it to Go's Time type with

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

Another option is to write custom UnmarshalJSON handler for the Metrics type:

  1. func (this *Metrics) UnmarshalJSON(data []byte) error {
  2. var f interface{}
  3. err := json.Unmarshal(data, &f)
  4. if err != nil { return err; }
  5. m := f.(map[string]interface{})
  6. for k, v := range m {
  7. switch k {
  8. case "metric_name": this.Name = v.(string)
  9. case "timestamp": this.Timestamp = time.Unix(int64(v.(float64)), 0)
  10. ...
  11. }
  12. }
  13. }

Then you have proper time.Time value in struct which makes working with it easier.

huangapple
  • 本文由 发表于 2017年1月11日 22:20:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/41593301.html
匿名

发表评论

匿名网友

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

确定