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 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件