Greenwich mean time
Coordinated universal time , Also known as universal time 、 World standard time 、 International coordination time .
Coordinated universal time is based on the atomic time and second , A time measurement system that is as close as possible to universal time in time .
CST It can be seen as the United States 、 Australia 、 Cuban or Chinese standard time .
CST It can be as follows 4 Abbreviations for different time zones :
Is a representation of time , International standards of international organization for Standardization ISO 8601 Is the representation of date and time , Its full name is 《 Data storage and exchange form · Information switching · Representation of date and time 》.
UTC+08 It's China's time .
Convert a time tuple to a string , for example , return ’Sat Jun 06 16:26:11 1998’.
The timestamp is converted to a string representing the local time , for example , return ’Sat Jun 06 16:26:11 1998’.
Timestamps converted to utc Time structure , for example
The timestamp is converted to a local time structure
take struct_time Turn to time stamp ( second )
Format the time tuple or time structure as a string
import time
print(time.strftime("%Y-%m-%S",time.localtime()))
# 2022-06-24
Convert a time string to a time structure
import time
print(time.strptime("2022-06-24","%Y-%m-%S"))
# time.struct_time(tm_year=2022, tm_mon=6, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=24, tm_wday=2, tm_yday=152, tm_isdst=-1)
second , millisecond , Microsecond , nanosecond , Base number 1k, I won't repeat
datetime Kuo is time Library extension
Common properties :
Create objects :
Common methods :
import datetime
# 2022-06-20 14:55:31.718297
print(datetime.datetime.utcnow())
# 2022-06-20 22:55:31.718297
print(datetime.datetime.now())
----------------------------------------
now = datetime.datetime.now()
utc_now = datetime.datetime.utcnow()
# 2022-06-20T22:59:11.174310
print(now.isoformat())
---------------------------------------
# 1
print(now.isoweekday())
----------------------------------------
# (2022, 25, 1)
print(now.isocalendar())
---------------------------------------
# 23:04:30.648577
print(now.time())
# 2022-06-20
print(now.date())
---------------------------------------
# 2022
print(now.strftime("%Y"))
--------------------------------------
# time.struct_time(tm_year=2022, tm_mon=6, tm_mday=20, tm_hour=23, tm_min=8, tm_sec=2, tm_wday=0, tm_yday=171, tm_isdst=-1)
print(now.timetuple())
-----------------------------------------
# 2022-06-20 23:09:02.547208+08:00
print(now.astimezone())
----------------------------------------
# 23:22:47.514078
print(now.timetz())
Method , Properties and datetime.datetime identical
Generally do not use
Time is allowed to be added or subtracted
import datetime
now = datetime.datetime.now()
# 2022-06-20 23:16:56.884229
print(now)
live = now + datetime.timedelta(seconds=10)
# 2022-06-20 23:17:06.884229
print(live)
# False
var = now > live
print(var)
timezone Class inheritance and base class tzinfo, Each instance of it represents a UTC The time zone defined by the fixed offset of .
from datetime import datetime, timezone, timedelta
tz1 = timezone(timedelta(hours=3), name='East 3')
dt = datetime(2019, 11, 21, 15, 12, 52, tzinfo = tz1)
# dt = datetime.datetime(2019, 11, 21, 15, 12, 52, tzinfo=datetime.timezone(datetime.timedelta(seconds=10800), 'East 3'))
dt.tzname()
# 'East 3'
timezone.utc
# datetime.timezone.utc
time The package provides functions for displaying and measuring time . The calendar is calculated in the Gregorian calendar .
time.Time Type represents time .
func timeDemo() {
now := time.Now() // Get the current time
fmt.Printf("current time:%v\n", now)
year := now.Year() // year
month := now.Month() // month
day := now.Day() // Japan
hour := now.Hour() // Hours
minute := now.Minute() // minute
second := now.Second() // second
fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}
The time stamp is from 1970 year 1 month 1 Japan (08:00:00GMT) The total number of milliseconds to the current time . It's also called Unix Time stamp (UnixTimestamp).
func timestampDemo() {
now := time.Now() // Get the current time
timestamp1 := now.Unix() // Time stamp
timestamp2 := now.UnixNano() // Nanosecond time stamp
fmt.Printf("current timestamp1:%v\n", timestamp1)
fmt.Printf("current timestamp2:%v\n", timestamp2)
}
Use time.Unix() Function to convert a timestamp to a time format .
func timestampDemo2(timestamp int64) {
timeObj := time.Unix(timestamp, 0) // Convert timestamps to time format
fmt.Println(timeObj)
year := timeObj.Year() // year
month := timeObj.Month() // month
day := timeObj.Day() // Japan
hour := timeObj.Hour() // Hours
minute := timeObj.Minute() // minute
second := timeObj.Second() // second
fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}
give an example
func main(){
now:=time.Now().Unix()
// 1655739004
fmt.Println(now)
timeObj:=time.Unix(now,0)
// 2022-06-20 23:30:04 +0800 CST
fmt.Println(timeObj)
}
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 .
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)
Go Used in language location To map specific time zones . The time zone (Time Zone) It is a definition of time divided according to different longitudes of countries and regions in the world , 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 .
// timezoneDemo Time zone example
func timezoneDemo() {
// There is no daylight saving time in China , Use a fixed 8 Hours of UTC time difference .
// For many other countries, summer time needs to be considered .
secondsEastOfUTC := int((8 * time.Hour).Seconds())
// FixedZone Return always use the given area name and offset (UTC East Second ) Of Location.
beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
// If the current system time zone database , You can load a location to get the corresponding time zone
// Load the time zone of New York
newYork, err := time.LoadLocation("America/New_York") // UTC-05:00
// Load the time zone of Shanghai
shanghai, err := time.LoadLocation("Asia/Shanghai") // UTC+08:00
// Load the time zone of Tokyo
tokyo, err := time.LoadLocation("Asia/Tokyo") // UTC+09:00
// 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)
timeInUTC := time.Date(2009, 1, 1, 12, 0, 0, 0, time.UTC)
sameTimeInBeijing := time.Date(2009, 1, 1, 20, 0, 0, 0, beijing)
sameTimeInNewYork := time.Date(2009, 1, 1, 7, 0, 0, 0, newYork)
// 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)
// true
fmt.Println(timesAreEqual)
// New York ( West five ) Than UTC On the evening of 5 Hours , So the above two times seem to be different 5 Hours , But it means the same time
timesAreEqual = timeInUTC.Equal(sameTimeInNewYork)
// true
fmt.Println(timesAreEqual)
}
func main() {
now := time.Now()
later := now.Add(time.Hour) // Current time plus 1 Hours later
fmt.Println(later)
}
func (t Time) Sub(u Time) Duration
func (t Time) Equal(u Time) bool
func (t Time) Before(u Time) bool
func (t Time) After(u Time) bool
Return to one time.C The Conduit ,time.Duration A point in time will be placed in this pipeline
func After(d Duration) <-chan Time {
return NewTimer(d).C
}
func Tick(d Duration) <-chan Time {
if d <= 0 {
return nil
}
return NewTicker(d).C
}
func tickDemo() {
ticker := time.Tick(time.Second) // Define a 1 Second interval timer
for i := range ticker {
fmt.Println(i)// Tasks that are performed every second
}
}
timer NewTimer It is triggered by waiting for how long , Trigger only once
func NewTimer(d Duration) *Timer {
c := make(chan Time, 1)
t := &Timer{
C: c,
r: runtimeTimer{
when: when(d),
f: sendTime,
arg: c,
},
}
startTimer(&t.r)
return t
}
func NewTicker(d Duration) *Ticker {
if d <= 0 {
panic(errors.New("non-positive interval for NewTicker"))
}
c := make(chan Time, 1)
t := &Ticker{
C: c,
r: runtimeTimer{
when: when(d),
period: int64(d),
f: sendTime,
arg: c,
},
}
startTimer(&t.r)
return t
}
Wait time function AfterFunc Is in After A callback function is added to the
time.AfterFunc(time.Second*1, F)
time.Format Function to format and output a time object as a text representation of the specified layout , It should be noted that Go Time formatted layouts are not common in languages Y-m-d H:M:S, But use 2006-01-02 15:04:05.000( The formula of memory is 2006 1 2 3 4 5).
// formatDemo Time format
func formatDemo() {
now := time.Now()
// The formatted template is 2006-01-02 15:04:05
// 24 hourly
fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))
// 12 hourly
fmt.Println(now.Format("2006-01-02 03:04:05.000 PM Mon Jan"))
// Write... After the decimal point 0, Because there is 3 individual 0 Therefore, the result of formatted output is also retained 3 Decimal place
fmt.Println(now.Format("2006/01/02 15:04:05.000")) // 2022/02/27 00:10:42.960
// Write... After the decimal point 9, Possible at the end will be omitted 0
fmt.Println(now.Format("2006/01/02 15:04:05.999")) // 2022/02/27 00:10:42.96
// 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"))
}
For parsing time objects from the time representation of text ,time The package provides time.Parse and time.ParseInLocation Two functions .
among time.Parse There is no need to specify additional time zone information during parsing .
// parseDemo Specify the time zone resolution time
func parseDemo() {
// Without a time zone indicator ,time.Parse return UTC Time
timeObj, err := time.Parse("2006/01/02 15:04:05", "2022/10/05 11:25:20")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(timeObj) // 2022-10-05 11:25:20 +0000 UTC
// In the case of a time zone indicator ,time.Parse Returns the time representation of the corresponding time zone
// RFC3339 = "2006-01-02T15:04:05Z07:00"
timeObj, err = time.Parse(time.RFC3339, "2022-10-05T11:25:20+08:00")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(timeObj) // 2022-10-05 11:25:20 +0800 CST
}
// parseDemo Parsing time
func parseDemo() {
now := time.Now()
fmt.Println(now)
// Load time zone
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
fmt.Println(err)
return
}
// Parse string time in the specified time zone and format
timeObj, err := time.ParseInLocation("2006/01/02 15:04:05", "2022/10/05 11:25:20", loc)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(timeObj)
fmt.Println(timeObj.Sub(now))
}