datetime - `foo.Seconds()`(类型 time.Duration)错误 - 不能使用 'd.Step.Seconds()'(类型 float64)作为类型 time.Duration
问题描述
我还是很陌生……所以,
我的问题的症结可以总结为:我正在准备将数据发送到远程 API,该 API 要求此字段为一种time.Duration
类型,我试图将其作为秒的字符串类型发送,###s
并将time.ParseDuration()
其发送到秒,但这是一个错误。
type Duration struct {
Duration time.Duration
Step time.Duration
}
// Needs to return a structure containing a duration formatted
// item and an item which is strictly in `seconds` format IE
// `int` or `float` `+` `"s"`.
func getDuration(pr *PromRequest) (Duration, error) {
duration, err := time.ParseDuration(pr.TimeRange)
if err != nil {
return Duration{}, nil
}
timeValue, err := strconv.Atoi(pr.TimeRange[:len(pr.TimeRange)-1])
if err != nil {
return Duration{}, err
}
// convert day value to day in hours
step := time.Duration(int64(24*timeValue) * 60 / 14)
return Duration{
Duration: duration,
Step: step, // <-- should be a time.Duration type...
}, nil
}
// \/\/hatever
func getMetricsWithRange(pr *PromRequest) (model.Value, error) {
d, err := getDuration(pr)
if err != nil {
e := fmt.Errorf("unable to translate received time into proper parsed time signature: %s", err)
fmt.Println(e)
return nil, err
}
...
r := v1.Range{
Start: time.Now().Add(-d.Duration),
End: time.Now(),
Step: d.Step.Seconds(), // <-- error lands here stating it's a float64
}
...
}
** 编辑 **
所以我想我现在理解我的误解了。time.Duration()
返回一个 time.Duration 类型,然后可以通过它发送.Seconds()
,它返回一个float64
。
在调用返回的结构的调用者中,当我打印实例变量的值时,它会是 NOT time.Duration
。我需要它在几秒钟内以time.Duration
的形式出现###s
,我知道time.Duration
这是行不通的。调用.Seconds()
它失败并出现错误Cannot use 'd.Step.Seconds()' (type float64) as type time.Duration
好的,所以我的误解来自几个因素。一:我真的很累。二:我是新手,一般来说是静态类型的语言。三:我认为我需要v1.Range.Step
在几秒钟内发送,这是错误的。time.Duration
我查看了将值转换为秒本身的接收代码。
现在,这个问题的很大一部分来自我的前端代码使用d
字符串中的字母在几天内发送一个值。time.ParseDuration()
不处理d
天数,所以days
我认为我会简单地以秒为单位传递一个时间值,而不是使用。
事实证明,解决此问题的最简单方法是简单地seconds
从前端发送。我永远无法让 go 代码正常工作。
解决方案
Duration.Seconds()
返回一个float64
值,因为持续时间值可能不是一整秒,并且它可能有十进制数字来表示确切的持续时间。如果Step
变量是四舍五入到最接近秒的持续时间,请使用Duration.Round(time.Second)
:
...
Step: Step.Round(time.Second)
这将为您提供一个四舍五入到一秒的持续时间。
如果你想获得秒值,那不是持续时间,它只是一个整数:
...
Step: int(Step.Seconds())
但是,在这种情况下,结果Step
不是持续时间,而只是一个给出秒数的 int 值。
推荐阅读
- android - 我在启动 android studio 时遇到问题?
- javascript - 从 FileReader() 返回结果?
- python - 从导入的 python 脚本中访问导入的 python 包时出现 NameError
- c# - 为什么我的 raycast 在几秒钟后停止工作?
- sql - 如何仅使用 SQL 合并行?
- google-cloud-tpu - 在谷歌云控制台上打开 tpus 页面时出错
- asp.net-core - 如何使用查询字符串将自定义 url 设置为操作路由 .net 核心
- objective-c - 是否可以使用 VImage 检查两个捕获的帧之间的差异?
- android - 列表未使用改造进入 recyclerview
- c++ - 如何 CMake 将库编译为我的应用程序源的一部分,而不是作为静态/共享库?