time模塊提供了一系列時(shí)間相關(guān)的方法,此外,同樣提供時(shí)間相關(guān)的模塊還有datetime和calendar。
注:時(shí)間戳是指格林威治時(shí)間1970年01月01日00時(shí)00分00秒(北京時(shí)間1970年01月01日08時(shí)00分00秒)起至現(xiàn)在的總秒數(shù)
下面列舉time中常用的一些方法
- time.asctime([t])
asctime()將一個(gè)tuple或者gmtime()返回的時(shí)間轉(zhuǎn)換成“Mon Jun 11 05:10:28 2018”格式
>>> print(time.asctime(time.gmtime()))
Mon Jun 11 05:10:28 2018
- time.gmtime([secs])
將時(shí)間戳轉(zhuǎn)換成struct_time格式的世界標(biāo)準(zhǔn)時(shí)間(UTC),如果不傳參數(shù)則默認(rèn)為當(dāng)前時(shí)間(UTC)
>>> print(time.gmtime(2345554657))
time.struct_time(tm_year=2044, tm_mon=4, tm_mday=29, tm_hour=14, tm_min=57, tm_sec=37, tm_wday=4, tm_yday=120, tm_isdst=0)
>>> print(time.gmtime())
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=11, tm_hour=5, tm_min=46, tm_sec=52, tm_wday=0, tm_yday=162, tm_isdst=0)
- time.localtime()
同time.gmtime(),不過返回的是本地時(shí)間
>>> print(time.localtime(), time.gmtime())
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=11, tm_hour=14, tm_min=0, tm_sec=47, tm_wday=0, tm_yday=162, tm_isdst=0) time.struct_time(tm_year=2018, tm_mon=6, tm_mday=11, tm_hour=6, tm_min=0, tm_sec=47, tm_wday=0, tm_yday=162, tm_isdst=0)
- time.ctime([secs])
將時(shí)間戳轉(zhuǎn)換成“Mon Jun 11 13:18:19 2018”格式,如果不傳參數(shù)則默認(rèn)為當(dāng)前的本地時(shí)間
>>> print(time.ctime())
Mon Jun 11 13:18:19 2018
>>> print(time.ctime(2345554657))
Fri Apr 29 22:57:37 2044
- time.time()
返回當(dāng)前時(shí)間的時(shí)間戳
>>> time.localtime(time.time())
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=11, tm_hour=14, tm_min=6, tm_sec=24, tm_wday=0, tm_yday=162, tm_isdst=0)
>>> time.gmtime(time.time())
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=11, tm_hour=6, tm_min=6, tm_sec=32, tm_wday=0, tm_yday=162, tm_isdst=0)
- time.mktime(t)
與localtime()相反,mktime()是將struct_time格式或9-tuple的時(shí)間轉(zhuǎn)化成時(shí)間戳??勺鳛閠ime.time()的輔助。但是mktime()必須傳入t參數(shù)。
>>> time.mktime(time.gmtime())
1528668787.0
- time.sleep(secs)
延遲執(zhí)行被調(diào)用線程
- time.strftime(format[, t])
將代表時(shí)間的元組或struct_time轉(zhuǎn)化為指定格式的字符串。如果不提供t參數(shù),則使用當(dāng)前本地時(shí)間(由localtime()返回)。格式指令參照官網(wǎng)
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Mon, 11 Jun 2018 06:53:37 +0000'