dsz1966 2019-01-07 09:05
浏览 41
已采纳

以Bash友好的方式格式化Go日期

Using buildah, I can find out the date my image was built at with this call:

buildah images --format '{{.CreatedAt}}' my_image

The --format argument is a Go template, as described for a related command.

This returns:

Nov 13, 2018 08:04

As far as I can tell that is my current timezone it uses, but it's not localised, and it's missing timezone information. If I feed the output into Linux's date like so:

date -d "`buildah images --format '{{.CreatedAt}}' my_container`" +%s

This gives me what I want, UNIX epoch seconds:

1542063840

However, since my '{{.CreatedAt}}' is a Go template that I should be able to format, how can I directly print out epoch seconds (or RFC-3339, etc) rather than relying on date.

As you can guess, I am an utter Go newbie and the documentation provided nothing I could copy-paste


NOTE: Following the below answer, enhancement request posted to the buildah issues db.

  • 写回答

1条回答 默认 最新

  • doukuang1897 2019-01-07 09:20
    关注

    Unfortunately you are out of luck.

    The parameter value passed to the template execution is of type imageOutputParams, which is declared in images.go:

    type imageOutputParams struct {
        Tag       string
        ID        string
        Name      string
        Digest    string
        CreatedAt string
        Size      string
    }
    

    As you can see, the CreatedAt field is of type string, not a time.Time, so you can't call time.Time methods on it. Neither can you do any useful date/time processing on it without custom registered functions. But since you're just supplying the template text, you can't register custom functions either.

    The template you pass is executed in function outputUsingTemplate() like this:

    err = tmpl.Execute(os.Stdout, params)
    

    Where params is a value of the above mentioned struct.

    Recommend the project owners to add a new field holding the CreatedAt timestamp as a time.Time value, so you can get the epoch seconds using Time.Unix(). The template would look like this then:

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

报告相同问题?

悬赏问题

  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 VUE项目怎么运行,系统打不开