本文詳細講述了python的內嵌time模塊的用法。分享給大家供大家參考之用。具體分析如下:
一、簡介
time模塊提供各種操作時間的函數
說明:一般有兩種表示時間的方式:
第一種是時間戳的方式(相對于1970.1.1 00:00:00以秒計算的偏移量),時間戳是惟一的
第二種以數組的形式表示即(struct_time),共有九個元素,分別表示,同一個時間戳的struct_time會因為時區不同而不同
year (four digits, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
DST (Daylight Savings Time) flag (-1, 0 or 1) 是否是夏令時
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
二、函數介紹
1.asctime()
asctime([tuple]) -> string
將一個struct_time(默認為當時時間),轉換成字符串
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
When the time tuple is not present, current time as returned by localtime()
is used.
2.clock()
clock() -> floating point number
該函數有兩個功能,
在第一次調用的時候,返回的是程序運行的實際時間;
以第二次之后的調用,返回的是自第一次調用后,到這次調用的時間間隔
示例:
import time if __name__ == '__main__': time.sleep(1) print "clock1:%s" % time.clock() time.sleep(1) print "clock2:%s" % time.clock() time.sleep(1) print "clock3:%s" % time.clock()
輸出:
clock1:3.35238137808e-006clock2:1.00004944763clock3:2.00012040636
其中第一個clock輸出的是程序運行時間
第二、三個clock輸出的都是與第一個clock的時間間隔
3.sleep(...)
sleep(seconds)
線程推遲指定的時間運行,經過測試,單位為秒,但是在幫助文檔中有以下這樣一句話,這關是看不懂
“The argument may be a floating point number for subsecond precision.”
4.ctime(...)
ctime(seconds) -> string
將一個時間戳(默認為當前時間)轉換成一個時間字符串
例如:
time.ctime()
輸出為:'Sat Mar 28 22:24:24 2009'
5.gmtime(...)
gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,tm_sec, tm_wday, tm_yday, tm_isdst)
將一個時間戳轉換成一個UTC時區(0時區)的struct_time,如果seconds參數未輸入,則以當前時間為轉換標準
6.localtime(...)
localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)
新聞熱點
疑難解答