dongqiu3254 2016-12-02 19:02
浏览 91
已采纳

Golang解析奇怪的日期格式

I'm working on a Parser which Parses log files from a game so I can do analysis on auctions made within the game, however the date format that's being written by the logger seems to be causing problems as the format seems to be custom written for the logger, an example datetime stamp looks like: [Wed Nov 23 23:26:10 2016] I try to Parse it with:

func (r *AuctionReader) extractSaleInformation(line string) {
    fmt.Println("Extracting information from: ", line)

    // Format mask for output
    layout := "DD-MM-YYYY hh:mm:ss"

    // Replace the square brackets so we're just left with the date-time string
    date := strings.TrimSpace(strings.Replace((strings.Split(line, "]")[0]), "[", "", -1))

    fmt.Println(time.Parse(date, layout))
}

When I attempt to Parse the above date-time string I get the following error:

0001-01-01 00:00:00 +0000 UTC parsing time "DD-MM-YYYY hh:mm:ss" as "Wed Nov 23 23:26:10 2016": cannot parse "DD-MM-YYYY hh:mm:ss" as "Wed Nov "

How am I able to get the parser to recognise this seemingly custom format, I will be saving this data to Mongo so I don't want to store the auction time as a string as I want to query the timestamps individually.

  • 写回答

1条回答 默认 最新

  • dtrvzd1171 2016-12-02 19:10
    关注

    Golang handle all date formatting in a unique way - it uses the reference time Mon Jan 2 15:04:05 MST 2006 (01/02 03:04:05PM '06 -0700) to show the pattern with which to format/parse a given time/string.

    So, to read the format "Wed Nov 23 23:26:10 2016" you would put the reference date into that format: "Mon Jan 2 15:04:05 2006", and then do:

    t, _ := time.Parse("Mon Jan 2 15:04:05 2006", "Wed Nov 23 23:26:10 2016")
    

    Then, to output it in the given format, if you wanted the format DD-MM-YYYY hh:mm:ss, you would put the reference time into that format: 02-01-2006 15:04:05, and then do:

    t.Format("02-01-2006 15:04:05")
    

    https://play.golang.org/p/VO5413Z7-z

    So basically, the main change is

    // Format mask for output
    layout := "DD-MM-YYYY hh:mm:ss"
    

    should be

    // Format mask for output
    layout := "02-01-2006 15:04:05"
    

    and

    time.Parse(date, layout)
    

    should be

    time.Parse(layout, date)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题