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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘