Python基礎系列講解——時間模塊詳解大全之time模塊

Python中提供處理時間日期相關的內置模塊有time、datetime和calendar。函數

time模塊中大多數函數調用了所在平臺C library 的同名函數,所以更依賴於操做系統層面,因此time模塊的有些函數與平臺相關,在不一樣的平臺上可能會有不一樣的效果,這點須要特別注意下,即time模塊的功能並不適用於全部平臺。spa

使用時須要導入time模塊,以下所示:操作系統

import time 

time模塊的時間表現的格式主要有如下三種:線程

  • timestamp時間戳。時間戳表示的是重新紀元開始按秒計算的偏移量,任何操做系統均可以運行time.gmtime(0)查找此係統的新紀元。對於時間戳的最大極限日期取決於系統中C函數庫所支持的日期,對於32位系統而言爲2038年,若是須要處理在所述範圍以外的日期,則須要考慮使用datetime模塊。以下所示:
#查找此係統的新紀元 print(time.gmtime(0)) #time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) #生成當前時間的timestamp print(time.time())#1556973222.546307 
  • struct_time時間元組,共有九個元素組,gmtime()、localtime()和strptime()都以時間元祖(struct_time)的形式返回。以下所示:

圖片描述

#生成struct_time print(time.localtime())#time.struct_time(tm_year=2019, tm_mon=5, tm_mday=11, tm_hour=12, tm_min=20, tm_sec=58, tm_wday=5, tm_yday=131, tm_isdst=0) 
  • format time格式化時間。格式化的結構可以使得時間更具備可讀性,主要有自定義格式和固定格式兩種,好比:
#生成format_time #生成自定義格式的時間表示格式 print(time.strftime("%Y-%m-%d %X",time.localtime()))#2019-05-04 20:40:01 #生成固定格式的時間表示格式 叉車配件 print(time.asctime(time.localtime()))#Sat May 11 19:45:16 2019 print(time.ctime(time.time()))#Sat May 11 19:45:16 2019 print(time.ctime(time.time()+10))#Sat May 11 19:45:26 2019 

time模塊中timestamp、struct_time和format time三種時間格式按如下方式轉換:code

#struct_time to timestamp note:time.localtime()——struct_time print(time.mktime(time.localtime())) #1556975223.0 # timestamp to struct_time 格林威治時間 note:time.time()——timestamp print(time.gmtime(time.time())) #time.struct_time(tm_year=2019, tm_mon=5, tm_mday=11, tm_hour=4, tm_min=20, tm_sec=58, tm_wday=5, tm_yday=131, tm_isdst=0) #format_time to struct_time print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')) #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6, tm_wday=3, tm_yday=125, tm_isdst=-1) #struct_time to format_time print(time.strftime("%Y-%m-%d %X"))#2019-05-11 08:45:48 print(time.strftime("%Y-%m-%d %X",time.localtime()))#2019-05-11 08:45:48 

關於time.asctime()和time.ctime()在上文中已經提到,能夠分別將struct_time和timestamp時間格式生成固定的format time格式。orm

time模塊中關於系統時間的處理有以下幾個函數:blog

time.clock()以秒爲單位返回當前CPU運行時間,用於衡量不一樣程序的耗時,比time.time()更實用。不過在Python3.3以後就不推薦使用,緣由是該方法依賴於操做系統,官方建議使用per_counter(返回系統運行時間)或process_time(返回進程運行時間)代替。以下所示:token

print(time.clock())#0.221209 #DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead 

time.perf_counter()返回系統的運行時間(計時器的精準時間),包含整個系統的睡眠時間。因爲返回值的基準點是未定義的,因此只有連續調用的結果之間的差纔是有效的。以下所示:進程

print(time.perf_counter())#4.373607855 time.sleep(5) print(time.perf_counter())#9.374290978 

time.process_time()返回當前進程執行CPU的時間總和,不包含睡眠時間.因爲返回值的基準點是未定義的,因此只有連續調用的結果之間的差纔是有效的。以下所示:圖片

print(time.process_time())#0.385954 time.sleep(5) print(time.process_time())#0.385982 

time.sleep(secs)推遲調用線程的運行,secs的單位是秒。以下所示:

time.sleep(5)
相關文章
相關標籤/搜索