Go의 시간 기간
Musfirah Waseem 2023년6월20일 Go Go Time

Go기간 변환은 여러 가지 방법으로 수행할 수 있습니다. time
라이브러리 및 time.duration
메서드는 시간을 계산하고 표시하는 데 자주 사용됩니다.
Duration
은 두 개의 정의된 시간 객체 사이에 경과된 시간을 int64
nanosecond
카운트로 나타냅니다.
기간 인스턴스 변환
나노초 | 1 |
마이크로초 | 1000 * 나노초 |
밀리초 | 1000 * 마이크로초 |
두번째 | 1000 * 밀리초 |
분 | 60 * 초 |
시간 | 60 * 분 |
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()) } }
출력:
( 1ns) = 1h25m10.918325664s ( 1µs) = 1h25m10.918326s ( 1ms) = 1h25m10.918s ( 1s) = 1h25m11s ( 2s) = 1h25m10s ( 1m0s) = 1h25m0s ( 10m0s) = 1h30m0s (1h0m0s) = 1h0m0s
위의 코드를 사용하면 모든 해당 기간을 부동 소수점 정수로 계산할 수 있습니다.
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()) }
출력:
27.77777777777778 1666.6666666666667 100000 Elapsed time in seconds: -0.0001
경과 시간은 프로세서가 지속 시간을 계산하는 데 걸린 시간을 알려줍니다.
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)) }
출력:
The time in Nanoseconds: 3600000000 The time in Microseconds: 3600000 The time in Milliseconds: 3600
위의 코드를 사용하면 숫자를 시간 인스턴스로 변환한 다음 time.Duration
이 시간 변환을 수행할 수 있습니다. 결국 시간 인스턴스는 다시 숫자로 변환됩니다.
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
작가: Musfirah Waseem
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