dsshsta97935 2018-09-22 19:04
浏览 1123
已采纳

将mysql datetime解析为golang时间

I have MySQL datetime in my table in the MySQL standard format like

"2018-09-19 18:26:32.000000"

and when I try converting it ti golang time using time.parse() function, I get the error that

parsing time "2018-09-19 18:26:32.000000": month out of range

I tried searching online and the format seems to be allowed and commonly used by many to successfully parse.

Can anyone help me with what I am missing? Below is the code snippet that I am using.

import (
    "fmt"
    "time"
)

layout := "2018-09-19 18:26:32.000000"
fmt.Println(val)
// prints 2018-09-19 18:26:32.000000
t, err := time.Parse(layout, val)
fmt.Println(fmt.Println(t.Unix()))
// prints -62135596800 
fmt.Println(err)
// prints parsing time "2018-09-19 18:26:32.000000": month out of range
  • 写回答

1条回答 默认 最新

  • duannao1920 2018-09-22 19:20
    关注

    Your layout is wrong, it should be "2006-01-02 15:04:05.000000". The documentation states:

    Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

    Mon Jan 2 15:04:05 -0700 MST 2006

    would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
    
        val := "2018-09-19 18:26:32.000000"
        layout := "2006-01-02 15:04:05.000000"
        t, _ := time.Parse(layout, val)
        fmt.Println(t.Unix()) // prints 1537381592
    }
    

    Outputs

    1537381592
    

    Try it here

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

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮