将CreationTimeStamp类型转换为字符串。

huangapple go评论82阅读模式
英文:

Convert CreationTimeStamp type to string

问题

我正在从pod.CreationTimeStamp获取时间,并尝试将其存储在一个变量中。如何将时间存储为字符串?

tmp := json_format{}
pods, _ := clientset.CoreV1().Pods(namespace).List(v1.ListOptions{LabelSelector:app_name})

for _, pod := range pods.Items {
    tmp.Creation_Time = append(tmp.Creation_Time, pod.CreationTimestamp) 
}

它给出了这个错误:cannot convert pod.ObjectMeta.CreationTimestamp (type "k8s.io/apimachinery/pkg/apis/meta/v1".Time) to type string

type json_format struct{
    Creation_Time string
}
英文:

I am getting time from pod.CreationTimeStamp and trying to store it in a variable.how can i store time in to string.

 tmp := json_format{}
 pods, _ := clientset.CoreV1().Pods(namespace).List(v1.ListOptions{LabelSelector:app_name})

 for _, pod := range pods.Items {
     tmp.Creation_Time = append(tmp.Creation_Time,pod.CreationTimestamp) 
}

Its giving this error: cannot convert pod.ObjectMeta.CreationTimestamp (type "k8s.io/apimachinery/pkg/apis/meta/v1".Time) to type string

type json_format struct{
Creation_Time string
}

答案1

得分: 2

CreationTimestamp转换为字符串,您可以使用String()方法。

示例:

timeInString := pod.CreationTimestamp.String()

您的代码:

tmp := json_format{}
pods, _ := clientset.CoreV1().Pods(namespace).List(v1.ListOptions{LabelSelector:app_name})

for _, pod := range pods.Items {
    tmp.Creation_Time = append(tmp.Creation_Time, pod.CreationTimestamp.String()) 
}

另一个更正请求:

Creation_Time字段应该是一个切片(即[]string),而不是单个字符串。

type json_format struct{
    Creation_Time []string
}
英文:

To convert CreationTimestamp to string you can use the method String().

Example:

timeInString := pod.CreationTimestamp.String()

Your code:

tmp := json_format{}
 pods, _ := clientset.CoreV1().Pods(namespace).List(v1.ListOptions{LabelSelector:app_name})

 for _, pod := range pods.Items {
     tmp.Creation_Time = append(tmp.Creation_Time,pod.CreationTimestamp.String()) 
}

Another correction request:

The Creatio_Time field should be slice (i.e. []string) instead of single string.

type json_format struct{
Creation_Time []string
}

huangapple
  • 本文由 发表于 2020年2月5日 13:58:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/60069771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定