dpikoto468637 2017-01-11 14:20
浏览 55
已采纳

将纪元时间戳解组为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条回答 默认 最新

  • dongyan5239 2017-01-11 15:24
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么