doulanyan6455 2018-11-06 22:58
浏览 64
已采纳

将Python解析为Golang-DateTime

I've been attempting to get a specific string output from pyhtons datetime (2006-01-02T15:04:05.000Z), so that I can easily parse it in golang using time.Parse.

I tried (in python)

datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')

Which will give me something like this: "2018-11-06T22:48:50.002750Z"

And when I try to parse it like this in Golang:

dtLayout := "2006-01-02T15:04:05.000Z"
dateStr := "2018-11-06T22:48:50.002750Z"

parsedDate, err := time.Parse(dtLayout, dateStr)
if err != nil {
    if err != nil {
        log.Printf("error: %v", err)
    }

I get this error:

2018/11/06 16:49:11 error: parsing time "2018-11-06T22:48:50.002750Z" as "2006-01-02T15:04:05.000Z": cannot parse "750Z" as "Z"

There's probably an easy way to do this using just milliseconds, but I'm stubborn and feel like I'm close.

  • 写回答

1条回答 默认 最新

  • dsolwotv00116 2018-11-06 23:09
    关注

    Zeros in the fractional seconds must match the number of characters exactly, and as your error states, the portion after 750Z doesn't match the corresponding portion of the format string.

    You can add the correct number of zeros, like "2006-01-02T15:04:05.000000Z", or use 9 as a more flexible format.

    dtLayout := "2006-01-02T15:04:05.9Z"
    

    https://play.golang.org/p/dyC0OXUnhhu

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料