Python的time模組中的常用方法整理
這篇文章主要介紹了Python的time模組中的常用方法整理,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微秒。可以使用該函數來記錄程式執行的時間。下面是一個簡單的例子:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
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模組中定義的表示時間的對象),下面是一個簡單的例子:
?
|
1
2
3
4
5
6
7
8
9
10
11 |
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對象作為參數,返回用秒數來表示時間的浮點數。例如:
?
|
1
2
3
4
5 |
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對象轉換為字串表示:
?
|
1
2
3
4
5
6
7
8 |
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對象:
?
|
1
2
3
4
5
6 |
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)
|
以上介紹的方法是time模組中最常用的幾個方法,在Python手冊中還介紹了其他的方法和屬性,如:time.timezone, time.tzname …感興趣的朋友可以參考Python手冊 time 模組。