kambi
kambi

Reputation: 3423

Unmarshaling epoch timestamp into 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

Upvotes: 3

Views: 8912

Answers (1)

ain
ain

Reputation: 22749

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.

Upvotes: 5

Related Questions