Tiempo Duración en Go
- Conversión de instancias de duración
- Usa el método
time.duration
- Calcule el tiempo transcurrido usando la biblioteca
time
- Convertir duraciones de tiempo en un número en Go

Go conversiones de duración de tiempo se puede hacer de varias maneras. La biblioteca tiempo
y los métodos tiempo.duración
se utilizan con frecuencia para calcular y mostrar el tiempo.
Tenga en cuenta que Duración
se refiere al tiempo transcurrido entre dos objetos de tiempo definidos como un recuento de int64
nanosegundos
.
Conversión de instancias de duración
nanosegundo | 1 |
Microsegundo | 1000 * Nanosegundo |
Milisegundo | 1000 * Microsegundo |
Segundo | 1000 * Milisegundo |
Minuto | 60 * Segundo |
Hora | 60 * Minuto |
Usa el método time.duration
package main import ( "fmt" "time" ) func main() { d, err := time.ParseDuration("1h25m10.9183256645s") if err != nil { panic(err) } count := []time.Duration{ time.Nanosecond, time.Microsecond, time.Millisecond, time.Second, 2 * time.Second, time.Minute, 10 * time.Minute, time.Hour, } for _, r := range count { fmt.Printf("(%6s) = %s\n", r, d.Round(r).String()) } }
Producción :
( 1ns) = 1h25m10.918325664s ( 1µs) = 1h25m10.918326s ( 1ms) = 1h25m10.918s ( 1s) = 1h25m11s ( 2s) = 1h25m10s ( 1m0s) = 1h25m0s ( 10m0s) = 1h30m0s (1h0m0s) = 1h0m0s
El código anterior nos permite calcular todas las duraciones respectivas como un número entero de coma flotante.
Calcule el tiempo transcurrido usando la biblioteca time
package main import ( "fmt" "time" ) func main() { var t time.Duration = 100000000000000 fmt.Println(t.Hours()) fmt.Println(t.Minutes()) fmt.Println(t.Seconds()) now := time.Now() time.Sleep(100000) diff := now.Sub(time.Now()) fmt.Println("Elapsed time in seconds: ", diff.Seconds()) }
Producción :
27.77777777777778 1666.6666666666667 100000 Elapsed time in seconds: -0.0001
El tiempo transcurrido nos dice cuánto tiempo le tomó al procesador calcular las duraciones de tiempo.
Convertir duraciones de tiempo en un número en Go
package main import ( "fmt" "time" ) func main() { timeInput := 3600 data := time.Duration(timeInput) * time.Millisecond fmt.Println("The time in Nanoseconds:", int64(data/time.Nanosecond)) fmt.Println("The time in Microseconds:", int64(data/time.Microsecond)) fmt.Println("The time in Milliseconds:", int64(data/time.Millisecond)) }
Producción :
The time in Nanoseconds: 3600000000 The time in Microseconds: 3600000 The time in Milliseconds: 3600
El código anterior nos permite convertir un número en una instancia de tiempo, y luego time.Duration
realiza conversiones de tiempo. Al final, la instancia de tiempo se vuelve a convertir en un número.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
LinkedIn