概述:time庫是python中處理時間的標准庫
import time
time.<b>()
包括3類函數:
常用
時間獲取:time.time() 時間戳,浮點數(秒) time.ctime()字符串 time.gmtime()時間元組
時間格式化:time.strftime()時間元組-->字符串 time.strptime()字符串-->時間元組
程序計時:time.sleep() time.perf_counter
--------------------時間獲取
>>> time.time() # 獲取系統當前時間戳,浮點數
1543109157.805488
>>> time.gmtime() # 獲取當前時間,返回時間元組(格林威治時間)
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=25, tm_hour=1, tm_min=45, tm_sec=7, tm_wday=6, tm_yday=329, tm_isdst=0)
gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,tm_sec, tm_wday, tm_yday, tm_isdst)
>>> time.localtime() # 獲取當前時間,返回時間元組(本地時間)
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=25, tm_hour=9, tm_min=39, tm_sec=4, tm_wday=6, tm_yday=329, tm_isdst=0)
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)
>>> time.ctime() # 獲取當前時間以易讀方式表示,返回字符串
'Sun Nov 25 09:27:39 2018'
ctime(seconds) -> string
Convert a time in seconds since the Epoch to a string in local time.
This is equivalent to asctime(localtime(seconds)). When the time tuple is
not present, current time as returned by localtime() is used.
time.mktime() # 把時間元組,轉換為秒
mktime(tuple) -> floating point number
>>> time.mktime(time.strptime('20181125 102030','%Y%m%d %H%M%S'))
1543112430.0
>>> time.asctime()
'Sun Nov 25 09:33:48 2018'
asctime([tuple]) -> string
----------------時間格式化
strftime(tpl, ts) # tpl是格式化模板字符串,用來定義輸出效果 。ts是時間元組
strftime(format[, tuple]) -> string
>>> time.strftime('%Y-%m-%d %H:%M:%S')
'2018-11-25 09:51:44'
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
time.strptime(str,tmp) # 把字符串格式的時間,轉換為時間元組
str是字符串形式的時間值 tpl是格式化模板字符串,用來定義輸入效果
>>> time.strptime('20181125','%Y%m%d')
time.struct_time(tm_year=2018, tm_mon=11, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=329, tm_isdst=-1)
-----------------------程序計時
測量時間 time.perf_counter()
返回一個CPU級別的精確時間計數值,單位為秒 由於這個計數值起點不確定,連續調用差值才有意義
>>> start = time.perf_counter()
>>> end = time.perf_counter()
>>> end - start
9.91788138099946
產生時間 time.sleep()
>>> time.sleep(2)
>>>