登录
首页 >  Golang >  Go问答

log15库会将纪元时间舍入到秒以记录

来源:stackoverflow

时间:2024-03-13 18:21:26 366浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《log15库会将纪元时间舍入到秒以记录》,聊聊,我们一起来看看吧!

问题内容

我希望在我的 golang 项目中的日志记录具有毫秒精度,当前使用 log15 库

问题是当我将其附加到上下文时,它会四舍五入到秒

newTimeWithMilliseconds := time.Unix(0, time.Now().UnixNano())

return log.FuncHandler(func(r *log.Record) {
     r.Ctx = append(r.Ctx, "time", newTimeWithMilliseconds)
     nextHandler.Log(r)
})

当我将其转换为字符串 newtimewithmilliseconds.string() 时,它可以工作,并且得到 "2018-09-25 15:07:45.25801232 -0500 pdt" ,但是当我不这样做时,小数点就会消失并且我得到 2018-09-25 15:07:45 -0700 pdt

我想保留时间格式而不是使用字符串,有人知道为什么会发生这种情况以及如何解决这个问题吗?


解决方案


您需要使用 time.Format 以您想要的精度显示 time.time 的值。除非您修改其值,否则它不会失去精度,您看到差异的原因只是由于调用 time.format 所使用的 layout 来打印您的时间。

当您使用 mytime.string() 时,使用的布局与其他打印时间的布局不同。

这就是为什么您需要使用 time.time 值但操纵它的打印方式,或者将其存储为格式化字符串。

参见Go by example

// go supports time formatting and parsing via
// pattern-based layouts.

package main

import "fmt"
import "time"

func main() {
    p := fmt.println

    // here's a basic example of formatting a time
    // according to rfc3339, using the corresponding layout
    // constant.
    t := time.now()
    p(t.format(time.rfc3339))

    // time parsing uses the same layout values as `format`.
    t1, e := time.parse(
        time.rfc3339,
        "2012-11-01t22:08:41+00:00")
    p(t1)

    // `format` and `parse` use example-based layouts. usually
    // you'll use a constant from `time` for these layouts, but
    // you can also supply custom layouts. layouts must use the
    // reference time `mon jan 2 15:04:05 mst 2006` to show the
    // pattern with which to format/parse a given time/string.
    // the example time must be exactly as shown: the year 2006,
    // 15 for the hour, monday for the day of the week, etc.
    p(t.format("3:04pm"))
    p(t.format("mon jan _2 15:04:05 2006"))
    p(t.format("2006-01-02t15:04:05.999999-07:00"))
    form := "3 04 pm"
    t2, e := time.parse(form, "8 41 pm")
    p(t2)

    // for purely numeric representations you can also
    // use standard string formatting with the extracted
    // components of the time value.
    fmt.printf("%d-%02d-%02dt%02d:%02d:%02d-00:00\n",
        t.year(), t.month(), t.day(),
        t.hour(), t.minute(), t.second())

    // `parse` will return an error on malformed input
    // explaining the parsing problem.
    ansic := "mon jan _2 15:04:05 2006"
    _, e = time.parse(ansic, "8:41pm")
    p(e)
}

输出

2009-11-10T23:00:00Z
2012-11-01 22:08:41 +0000 UTC
11:00PM
Tue Nov 10 23:00:00 2009
2009-11-10T23:00:00+00:00
0000-01-01 20:41:00 +0000 UTC
2009-11-10T23:00:00-00:00
parsing time "8:41PM" as "Mon Jan _2 15:04:05 2006": cannot parse "8:41PM" as "Mon"

亲自尝试一下here

理论要掌握,实操不能落!以上关于《log15库会将纪元时间舍入到秒以记录》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>