当前位置:网站首页>Go common standard library -time
Go common standard library -time
2022-07-25 02:39:00 【go|Python】
List of articles
go Common standard library -time
Basic use
time.Time Type represents time . We can go through time.Now() Function to get the current time object , Then obtain the date, month, hour, minute, second and other information of the time object .
func main() {
t := time.Now()
fmt.Println(t) // 2022-07-19 09:50:29.8980644 +0800 CST m=+0.003829601
year := t.Year() // year
month := t.Month() // month
day := t.Day() // Japan
hour := t.Hour() // Hours
minute := t.Minute() // minute
second := t.Second() // second
fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second) // 2022-07-19 09:50:29
}
func main() {
time.Sleep(3*time.Second) // A dead sleep 3 second
}
Time stamp
The time stamp is from 1970 year 1 month 1 Japan (08:00:00GMT) Computer and a Nian , The total number of milliseconds to the current time . It's also called Unix Time stamp (UnixTimestamp).
func main() {
t := time.Now()
timestamp1 := t.Unix() // Time stamp
timestamp2 := t.UnixNano() // Nanosecond time stamp
fmt.Printf("current timestamp1:%v\n", timestamp1) // current timestamp1:1658195429
fmt.Printf("current timestamp2:%v\n", timestamp2) // current timestamp2:1658195429898064400
}
Timestamp objects can also be accessed through time.Unix() Convert to formatted time object , And through .Format() Method specifies the format and outputs
func main() {
timestamp := time.Now().Unix()
tm := time.Unix(timestamp,0) // timestamp It can be released int64 A number of bit type as a timestamp
fmt.Printf(tm.Format("2006-01-02 03:04:05 PM")) // 2022-07-19 09:57:03 AM
fmt.Printf(tm.Format("02/01/2006 15:04:05 PM")) // 19/07/2022 09:57:03 AM
}
The time interval
time.Duration yes time A type of package definition , It represents the time between two time points , In nanoseconds .time.Duration A time interval , The longest period that can be expressed is about 290 year .
time The constants of the interval type defined in the package are as follows :
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
//time.Duration Express 1 nanosecond ,time.Second Express 1 second .
Time operation
Add
Time adds up
func (t Time) Add(d Duration) Time
for instance , seek 24 Hours later :
func main() {
var now time.Time = time.Now()
lastTime:=now.Add(24*time.Hour)
fmt.Println(lastTime)
}
Sub
Find the difference between two times
func (t Time) Sub(u Time) Duration
If the result exceeds Duration The maximum value that can be expressed / minimum value , Will return the maximum / minimum value .
To get a point in time Time-Duration, have access to t.Add(-Duration)
Calculate the difference between two time objects , If you calculate the difference between time and time interval , Use Add
func main() {
var start time.Time = time.Now()
var end=time.Now()
fmt.Println(end.Sub(start))
}
Equal
func (t Time) Equal(u Time) bool
Determine if the two times are the same , Will consider the impact of time zone , Therefore, the standard time of different time zones can also be correctly compared .
This method and use ==( Double equal sign ) Different , This method also compares location and time zone information .
Before
func (t Time) Before(u Time) bool
If t The representative's time is u Before , Return to true ; Otherwise return false .
After
func (t Time) After(u Time) bool
If t The representative's time is u after , Return to true ; Otherwise return false .
func main() {
var start time.Time = time.Now()
var end=time.Now()
fmt.Println(end.Before(start))
fmt.Println(end.After(start))
}
Time format
There's a way for time types Format format , It should be noted that Go Formatting time templates in languages is not common Y-m-d H:M:S But use Go The birth time of 2006 year 1 month 2 Number 15 spot 04 branch ( The formula of memory is 2006 1 2 3 4)
- 2006 It refers to the year (Y)
- 01 It refers to the month (m)
- 02 On behalf of the sun (d)
- 15 When referring to (H)
- 04 Refers to points (M)
- 05 Refers to seconds (S)
// If you want to format it as 12 Hour mode , Need to specify PM
// If you want to keep the specified number of decimal places, write 0, If you want to omit the last possible 0 Just write 9
func main() {
var now time.Time = time.Now()
fmt.Println(now.Format("2006-01-02"))
fmt.Println(now.Format("2006 year 01 month 02 Japan "))
fmt.Println(now.Format("2006-01-02 15:02:05"))
fmt.Println(now.Format("2006-01-02 03:04:05 PM"))
// Write... After the decimal point 0, Because there is 4 individual 0 Therefore, the result of formatted output is also retained 4 Decimal place
fmt.Println(now.Format("2006-01-02 15:04:05.0000")) //2022-03-19 00:50:09.7412
// Write... After the decimal point 9, If the end is 0, Will be omitted
fmt.Println(now.Format("2006-01-02 15:04:05.9999"))
// Format only the hours, minutes and seconds
fmt.Println(now.Format("15:04:05"))
// Format only the date part
fmt.Println(now.Format("2006.01.02"))
}
Format the string into time
func main() {
timeObj,err:=time.Parse("2006-01-02 15:04:05.9999","2022-03-19 00:10:42.96")
if err != nil {
fmt.Println(" Conversion error ",err)
}
// Default to utc Time
fmt.Println(timeObj)
fmt.Println(timeObj.Year())
fmt.Println(timeObj.Month())
fmt.Println(timeObj.Day())
fmt.Println(timeObj.Hour())
fmt.Println(timeObj.Minute())
fmt.Println(timeObj.Second())
now:=time.Now()
res:=now.Sub(timeObj)
fmt.Println(res) // The current time minus the converted time , Poor discovery 8 Hours
//time.ParseInLocation The function needs to specify additional time zone information when parsing .
// Parse string time in the specified time zone and format
loc, err := time.LoadLocation("Asia/Shanghai")
timeObj2, err := time.ParseInLocation("2006-01-02 15:04:05", "2022-03-19 00:10:42", loc)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(timeObj2)
res=now.Sub(timeObj2)
fmt.Println(res) // This time is normal
}
The time zone
The world is divided into 24 Time zone . China is almost across the world 5 Time zone , However, for convenience, only the standard time of Dongba time zone, i.e. Beijing time, shall prevail
func main() {
shanghaiTime, err := time.LoadLocation("Asia/Shanghai") // Only Chongqing Asia/chongqin, Shanghai Asia/Shanghai.. Some cities
//tokyo, err := time.LoadLocation("Asia/Tokyo")
if err != nil {
fmt.Println(" Error loading ", err)
return
}
fmt.Println(shanghaiTime)
// To create a time object, you need to specify a location . Common locations are time.Local( Local time ) and time.UTC(UTC Time ).
//timeInLocal := time.Date(2009, 1, 1, 20, 0, 0, 0, time.Local) // System local time
timeInUTC := time.Date(2022, 3, 15, 12, 3, 4, 0, time.UTC)
sameTimeInBeijing := time.Date(2022, 3, 15, 20, 3, 4, 0, shanghaiTime)
// Beijing time. ( East eight ) Than UTC Good morning! 8 Hours , So the above two times seem to be different 8 Hours , But it means the same time
timesAreEqual := timeInUTC.Equal(sameTimeInBeijing)
fmt.Println(timesAreEqual)
}
Timing task
Please refer to go timer One article
边栏推荐
- When executing SQL query statements in MySQL database, the underlying implementation principle (ultra detailed)
- Physical experiment simulation
- Ten year structure and five-year Life-03 trouble as a technical team leader
- Rolling division, Young's matrix and three-step flip
- SQL recursive follow-up
- Pagoda workman WSS reverse proxy socket legal domain name applet chat remove port
- Componentization and modularization
- R language uses logistic regression, ANOVA, outlier analysis and visual classification iris iris data set
- 6. Object storage
- It's still a synchronization problem
猜你喜欢

"I gave up programming and wrote a 1.3 million word hard science fiction."

Visualization of correlation coefficient matrix

Sword finger offer 11. rotate the minimum number of the array

Is it necessary to increase the number of milliseconds and save several KB of memory in the program?

Babbitt | metauniverse daily must read: Dubai launched the national metauniverse strategy, which plans to increase the number of related companies of metauniverse by five times in the next five years

On Calc optimization of calcite

Apk packaging process

Sequence diagram of UML diagram series

Use SAP ui5 application to consume create and delete operations of OData in business application studio

Why can't reading more books improve your writing?
随机推荐
Is it necessary to increase the number of milliseconds and save several KB of memory in the program?
It's still a synchronization problem
Digital commerce cloud fine chemical industry management platform integrated informatization solution
"Introduction to interface testing" punch in to learn day07: websocket interface: how to test a completely unfamiliar protocol interface?
DNA helped solve the outstanding case 30 years ago. The suspect strangled his girlfriend because he fell in love with his roommate. He was already the CEO of the technology company when he was arreste
Tp5.1 initialize initialization method (not \u initialize)
B2B e-commerce trading platform of heavy metal industry: breaking the state of data isolation and improving the benefits of heavy metal industry
Simulate the implementation of strstr
SQL recursive follow-up
Introduction to web security telent testing and defense
Sequence diagram of UML diagram series
See you in Suzhou! "Cloud Intelligence Technology Forum - industry special" will be held soon
[system design] distributed key value database
Cloud native platform, let edge applications play out!
Automatic backup of Linux server PostgreSQL database
Summary and sorting of XSS (cross site script attack) related content
"No such plugin: cloudbees folder" solution appears when Jenkins selects the recommended plug-in for the first time
Keepalivetime=0 description of ThreadPoolExecutor
Execution methods with static code blocks and child and parent classes
Ten year structure and five-year Life-03 trouble as a technical team leader