《Python實戰-構建基於股票的量化交易系統》小冊子,雖然主要側重於 Python 實戰講解,但在內容設計上提供了前置基礎章節幫助讀者快速掌握基礎工具的使用,所以小冊適合的人羣僅具有Python最基礎編程經驗便可。編程
同時咱們會持續更新一些關於Python和量化相關的基礎文章,幫助你們夯實基礎。接下來咱們介紹下Python中時間模塊大全之time。bash
Python中提供處理時間日期相關的內置模塊有time、datetime和calendar。markdown
time模塊中大多數函數調用了所在平臺C library 的同名函數,所以更依賴於操做系統層面,因此time模塊的有些函數與平臺相關,在不一樣的平臺上可能會有不一樣的效果,這點須要特別注意下,即time模塊的功能並不適用於全部平臺。函數
使用時須要導入time模塊,以下所示:工具
import time
複製代碼
time模塊的時間表現的格式主要有如下三種:spa
#查找此係統的新紀元 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 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) 複製代碼
struct_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 複製代碼
format time結構化格式表示含義以下:線程
time模塊中timestamp、struct_time和format time三種時間格式按如下方式轉換:設計
#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格式。code
time模塊中關於系統時間的處理有以下幾個函數:
time.clock()以秒爲單位返回當前CPU運行時間,用於衡量不一樣程序的耗時,比time.time()更實用。不過在Python3.3以後就不推薦使用,緣由是該方法依賴於操做系統,官方建議使用per_counter(返回系統運行時間)或process_time(返回進程運行時間)代替。以下所示:
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) 複製代碼
關於完整代碼能夠加入小冊交流羣獲取。更多的量化交易內容歡迎你們訂閱小冊閱讀!!