本文詳細(xì)講述了python的內(nèi)嵌time模塊的用法。分享給大家供大家參考之用。具體分析如下:
一、簡介
time模塊提供各種操作時(shí)間的函數(shù)
說明:一般有兩種表示時(shí)間的方式:
第一種是時(shí)間戳的方式(相對于1970.1.1 00:00:00以秒計(jì)算的偏移量),時(shí)間戳是惟一的
第二種以數(shù)組的形式表示即(struct_time),共有九個(gè)元素,分別表示,同一個(gè)時(shí)間戳的struct_time會(huì)因?yàn)闀r(shí)區(qū)不同而不同
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) 是否是夏令時(shí)
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.
二、函數(shù)介紹
1.asctime()
asctime([tuple]) -> string
將一個(gè)struct_time(默認(rèn)為當(dāng)時(shí)時(shí)間),轉(zhuǎn)換成字符串
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
該函數(shù)有兩個(gè)功能,
在第一次調(diào)用的時(shí)候,返回的是程序運(yùn)行的實(shí)際時(shí)間;
以第二次之后的調(diào)用,返回的是自第一次調(diào)用后,到這次調(diào)用的時(shí)間間隔
示例:
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
其中第一個(gè)clock輸出的是程序運(yùn)行時(shí)間
第二、三個(gè)clock輸出的都是與第一個(gè)clock的時(shí)間間隔
3.sleep(...)
sleep(seconds)
線程推遲指定的時(shí)間運(yùn)行,經(jīng)過測試,單位為秒,但是在幫助文檔中有以下這樣一句話,這關(guān)是看不懂
“The argument may be a floating point number for subsecond precision.”
4.ctime(...)
ctime(seconds) -> string
將一個(gè)時(shí)間戳(默認(rèn)為當(dāng)前時(shí)間)轉(zhuǎn)換成一個(gè)時(shí)間字符串
例如:
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)
將一個(gè)時(shí)間戳轉(zhuǎn)換成一個(gè)UTC時(shí)區(qū)(0時(shí)區(qū))的struct_time,如果seconds參數(shù)未輸入,則以當(dāng)前時(shí)間為轉(zhuǎn)換標(biāo)準(zhǔn)
6.localtime(...)
localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)
新聞熱點(diǎn)
疑難解答
圖片精選