Convert CreationTimeStamp type to string

2/5/2020

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
}
-- Sai Vamsi
go
kubernetes
kubernetes-go-client

1 Answer

2/5/2020

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
}
-- Kamol Hasan
Source: StackOverflow