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 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 游戏盾如何溯源服务器真实ip?
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥50 win10链接MySQL
  • ¥15 抖音看过的视频,缓存在哪个文件