Formatting Time Output in Golang

Keywords: Operation & Maintenance Python Linux shell Unix

Usually we need to format the output of time in the process of program processing, so that users or other programs can recognize time more friendly. This paper records how to format time in the process of using golang language. Usually we can use linux shell to format the time conveniently:

sh-4.1$ date
2018 Tuesday, 18 September 2002:49:06 CST
sh-4.1$ date "+%Y-%m-%dT %H:%M:%S"
2018-09-18T 12:49:07

%y  Year of expression(2018->18)
%h  Express X month(9 month)

# Direct output timestamp
sh-4.1$ date +%s
1537248887

In python, we might format the time as follows: The parameters of formatting time in python are consistent with those in linux shell

In [1]: import datetime
In [2]: datetime.datetime.now().strftime('%Y-%m-%dT %H:%M:%S')
Out[2]: '2018-09-18T 13:31:35'

# Time Stamp Conversion According to a Certain Time Format
In [3]: import time
In [4]: int(time.mktime(time.strptime('2018-09-18T 13:31:35', "%Y-%m-%dT %H:%M:%S")))
Out[4]: 1537248695

# Get the current and the previous day, the first two days
import datetime
now = datetime.datetime.now()
last1 = now+datetime.timedelta(days=-1)
last2 = last1+datetime.timedelta(days=-1)
print(now.strftime('%Y-%m-%d %H:%M:%S'))
print(last1.strftime('%Y-%m-%d %H:%M:%S'))
print(last2.strftime('%Y-%m-%d %H:%M:%S'))

$ python testdate.py
2018-09-28 17:08:35
2018-09-27 17:08:35
2018-09-26 17:08:35

In Golang, we want to format the time as follows:

➜   ✗ cat test-time.go
package main
import (
	"time"
	"fmt"
)
func main() {
	now := time.Now()
	timestamp := now.Unix()
	fmt.Println("time stamp:"+fmt.Sprintf("%d",timestamp))
	fmt.Printf("current time:%d-%d-%dT %d:%d:%d\n",now.Year(),now.Month(),now.Day(),now.Hour(),now.Minute(),now.Second())
}

➜   ✗ go run test.go
//Time stamp: 1537251120
//Current time: 2018-9-18T 14:12:0
➜   ✗ go run test.go
//Time stamp: 1537251122
//Current time: 2018-9-18T 14:12:2

Some methods of using the Time structure in golang can format the current time very conveniently and friendly, but more careful friends may find some problems even when using the Time structure method to get specific time (year, month, day, time, second), these methods belong to lazy output, such as now in September, when using * Time.Month() will output 9 instead of 09;*Time.Second() When encountering single-digit seconds, it does not make up for zero in ten bits. At this time, the time-related method can not match the standard time format, so the Format method is needed to format the time.

fmt.Println(now.Format("2006-01-02T 15:04:05"))
# The output format is:
2018-09-18T 14:25:01

# Output only: month-day (09-18)
fmt.Println(now.Format("01-02"))

Welcome to my public number

Posted by tthmaz on Thu, 03 Oct 2019 02:40:46 -0700