I have a following function which calculated time since startTime
, uptime: time.Since(startTime).String()
.
This returns time as follows:
"uptime": "3m54.26744075s"
How do I convert time to be in seconds, as follows:
"uptime": "123456789"
time.Since()
returns you a value of type time.Duration
which has a Duration.Seconds()
method, just use that:
secs := time.Since(startTime).Seconds()
This will be of type float64
. If you don't need the fraction part, just convert it to int
, e.g. int(secs)
. Alternatively you may divide the time.Duration
value with time.Second
(which is the number of nanoseconds in a second), and you'll get to an integer seconds value right away:
secs := int(time.Since(startTime) / time.Second)
(Note that the int
conversion in this last example is not to drop the fraction part because this is already an integer division, but it's rather to have the result as a value of type int
instead of time.Duration
.)
Also see related question: Conversion of time.Duration type microseconds value to milliseconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With