程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

go time,python time,datetime

編輯:Python

Time format

GMT:

Greenwich mean time

UTC:

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:

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 :

  1. Central time :Central Standard Time (USA) UT-6:00
  2. Central Australia time :Central Standard Time (Australia) UT+9:30
  3. China standard time :China Standard Time UT+8:00
  4. Cuba standard time :Cuba Standard Time UT-4:00

ISO:

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 》.

explain

UTC+08 It's China's time .

python Time for

time

def asctime(p_tuple=None)->string

Convert a time tuple to a string , for example , return ’Sat Jun 06 16:26:11 1998’.

def ctime(seconds=None)->string

The timestamp is converted to a string representing the local time , for example , return ’Sat Jun 06 16:26:11 1998’.

def gmtime(seconds=None)->struct_time

Timestamps converted to utc Time structure , for example

def localtime(seconds=None)->struct_time

The timestamp is converted to a local time structure

def mktime(struct_time)->second

take struct_time Turn to time stamp ( second )

def strftime(format, p_tuple=None)

Format the time tuple or time structure as a string

import time
print(time.strftime("%Y-%m-%S",time.localtime()))
# 2022-06-24

strptime(string, format) -> struct_time

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)

def time(),def time_ns()

second , millisecond , Microsecond , nanosecond , Base number 1k, I won't repeat

datetime

datetime Kuo is time Library extension

  1. datetime.date: Date representation class , It can mean year, month, day, etc .
  2. datetime.time: Time representation class , It can be expressed in hours, minutes, seconds and milliseconds .
  3. datetime.datetime: Date time related classes , Functional coverage date and time class .
  4. datetime.timedelta: There are classes related to time intervals .
  5. datetime.tzinfo: Time zone related information representation class .

datetime.datetime class

Common properties :

  1. .min: return datetime Minimum time object .
  2. .max: return datetime Maximum time object .
  3. .year:datetime The annual attribute value of the object .
  4. .month:datetime Object's monthly attribute value .
  5. .day:datetime Object's daily attribute value .
  6. .hour:datetime The time attribute value of the object .
  7. .minute:datetime The sub attribute value of the object .
  8. .second:datetime Property value of object . second
  9. .microsecond:datetime The microsecond attribute value of the object .

Create objects :

  1. datetime.datetime.now(): Convert timestamps to datetime object , The default timestamp is time.time()
  2. datetime.datetime.utcnow(): ditto , To utc
  3. datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0): Specify the year, month and day to create datetime object
  4. datetime.fromtimestamp(timestamp, tz=None) Convert a timestamp to a datetime object
  5. utcfromtimestamp(timestamp) take utc The timestamp is converted to an object

Common methods :

  1. isoformat(): use ISO 0861 Standard display time , And return a string .
  2. isoweekday: Calculates the week based on the date and returns (1-7, integer ).
  3. strftime(format): According to the format string format Format and display , And return a string
  4. isocalendar(): return (year, Week , What day of the week )
  5. utcnow(): return utc The time of the datetime object
  6. time(): return datetime The time corresponding to the object
  7. date(): return datetime The date corresponding to the object
  8. datetime.strptime(cls, date_string, format): Class method , Format the string as datetime object
  9. timetuple(): take datetime Object becomes a time tuple
  10. astimezone(self, tz=None) According to the specified time zone parameter tz Return to one DateTime example
  11. timetz() Return to one time object , contain datetime The time part of the object , contain tzinfo
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())

datetime.date class

Method , Properties and datetime.datetime identical

datetime.time class

Generally do not use

datetime.timedelta class

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)

datetime.tzinfo class

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

go Time for

time The package provides functions for displaying and measuring time . The calendar is calculated in the Gregorian calendar .

Time type

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)
}

Time stamp

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)
}

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 .

const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)

The time zone

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)
}

Time operation

Add

func main() {

now := time.Now()
later := now.Add(time.Hour) // Current time plus 1 Hours later 
fmt.Println(later)
}

reduce

func (t Time) Sub(u Time) Duration

Whether it is equal or not

  1. 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 .
  2. This method and use t==u Different , This method also compares location and time zone information .
 func (t Time) Equal(u Time) bool

Whether in front of

 func (t Time) Before(u Time) bool

After

func (t Time) After(u Time) bool

Timer

After function

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
}

Tick function

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 
}
}

NewTimer()

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
}

NewTicker()

  1. Timer NewTicker Is to set how often it is triggered , It's a continuous trigger .
  2. ticker As long as the definition is complete , From this moment on , No other operation is required , Trigger every fixed time .
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
}

AfterFunc

Wait time function AfterFunc Is in After A callback function is added to the

time.AfterFunc(time.Second*1, F)

Time format

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"))
}

Time to parse string format

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))
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved