python的time库有哪些方法_Python的time模块中的常用方法整理
在應用程序的開發過程中,難免要跟日期、時間處理打交道。如:記錄一個復雜算法的執行時間;網絡通信中數據包的延遲等等。Python中提供了time, datetime calendar等模塊來處理時間日期,今天對time模塊中最常用的幾個函數作一個介紹。
time.time
time.time()函數返回從1970年1月1日以來的秒數,這是一個浮點數。
time.sleep
可以通過調用time.sleep來掛起當前的進程。time.sleep接收一個浮點型參數,表示進程掛起的時間。
time.clock
在windows操作系統上,time.clock() 返回第一次調用該方法到現在的秒數,其精確度高于1微秒。可以使用該函數來記錄程序執行的時間。下面是一個簡單的例子:
import time
print time.clock()
#1
time.sleep(2)
print time.clock()
#2
time.sleep(3)
print time.clock()
#3
#---- result
#3.91111160776e-06
#1.99919151736
#4.99922364435
time.gmtime
該函數原型為:time.gmtime([sec]),可選的參數sec表示從1970-1-1以來的秒數。其默認值為time.time(),函數返回time.struct_time類型的對象。(struct_time是在time模塊中定義的表示時間的對象),下面是一個簡單的例子:
import time
print time.gmtime()
#獲取當前時間的struct_time對象
print time.gmtime(time.time() - 24 * 60 * 60)
#獲取昨天這個時間的struct_time對象
#---- result
#time.struct_time(tm_year=2009, tm_mon=6, tm_mday=23, tm_hour=15, tm_min=16, tm_sec=3, tm_wday=1, tm_yday=174, tm_isdst=0)
#time.struct_time(tm_year=2009, tm_mon=6, tm_mday=22, tm_hour=15, tm_min=16, tm_sec=3, tm_wday=0, tm_yday=173, tm_isdst=0)
time.localtime
time.localtime與time.gmtime非常類似,也返回一個struct_time對象,可以把它看作是gmtime()的本地化版本。
time.mktime
time.mktime執行與gmtime(), localtime()相反的操作,它接收struct_time對象作為參數,返回用秒數來表示時間的浮點數。例如:
import time
#下面兩個函數返回相同(或相近)的結果
print time.mktime(time.localtime())
print time.time()
time.strftime
time.strftime將日期轉換為字符串表示,它的函數原型為:time.strftime(format[, t])。參數format是格式字符串(格式字符串的知識可以參考:time.strftime),可選的參數t是一個struct_time對象。下面的例子將struct_time對象轉換為字符串表示:
import time
print time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
print time.strftime('Weekday: %w; Day of the yesr: %j')
#---- result
#2009-06-23 15:30:53
#Weekday: 2; Day of the yesr: 174
time.strptime
按指定格式解析一個表示時間的字符串,返回struct_time對象。該函數原型為:time.strptime(string, format),兩個參數都是字符串,下面是一個簡單的例子,演示將一個字符串解析為一個struct_time對象:
import time
print time.strptime('2009-06-23 15:30:53', '%Y-%m-%d %H:%M:%S')
#---- result
#time.struct_time(tm_year=2009, tm_mon=6, tm_mday=23, tm_hour=15, tm_min=30, tm_sec=53, tm_wday=1, tm_yday=174, tm_isdst=-1)
總結
以上是生活随笔為你收集整理的python的time库有哪些方法_Python的time模块中的常用方法整理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ug11许可证文件路径安装在哪_Matl
- 下一篇: python接口测试面试题及答案_100