time模塊提供了一些用于管理時間和日期的C庫函數,由于它綁定到底層C實現,因此一些細節會基于具體的平臺。
一.壁掛鐘時間
1.time()
time模塊的核心函數time(),它返回紀元開始的秒數,返回值為浮點數,具體精度依賴于平臺。
>>>importtime
>>>time.time()
1460599046.85416
2.ctime()
浮點數一般用于存儲和比較日期,但是對人類不友好,要記錄和打印時間,可以使用ctime()。
>>>importtime
>>>time.ctime()
'Thu Apr 14 10:03:58 2016'
>>>later=time.time()+5
>>>time.ctime(later)
'Thu Apr 14 10:05:57 2016'
二.處理器時鐘時間
clock()返回處理器時鐘時間,它的返回值一般用于性能測試與基準測試。因此它們反映了程序的實際運行時間。
>>>importtime
>>>time.clock()
0.07
三.時間組成
time模塊定義了struct_time來維護時間和日期,其中分開存儲各個組成部分,以便訪問。
import time
def show_struct(s):
print'tm_year:", s.tm_year
print 'tm_mon:", s.tm_mon
print "tm_mday:", s.tm_mday
print "tm_hour:",s.tm_hour
print "tm_min:", s.tm_min
print "tm_sec:", s.tm_sec
print "tm_wday:", s.tm_wday
print "tm_yday:",s.tm_yday
show_struct(time.gmtime())
show_struct(time.localtime())
gmtime()用于獲取UTC時間,localtime()用于獲取當前時區的當前時間,UTC時間實際就是格林尼治時間,它與中國時間的時差為八個小時。
locatime() = gmtime() + 8hour
四.處理時區
1.獲取時間差
>>>importtime
>>>time.timezone/3600
-8
2.設置時區
ZONES=["GMT","EUROPE/Amsterdam']
for zone in ZONES:
os.environ["TZ"]=zone
time.tzset()
五.解析和格式化時間
time模塊提供了兩個函數strptime()和strftime(),可以在struct_time和時間值字符串之間轉換。
1.strptime()
用于將字符串時間轉換成struct_time格式:
>>>now=time.ctime()
>>>time.strptime(now)
time.struct_time(tm_year=2016,tm_mon=4,tm_mday=14,tm_hour=10,tm_min=48,tm_sec=40,tm_wday=3,tm_yday=105,tm_isdst=-1)
2.strftime()
用于時間的格式化輸出
>>>from time importgmtime,strftime
>>>strftime("%a, %d %b %Y %H:%M:%S +0000",gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'
3.mktime()
用于將struct_time轉換成時間的浮點數表示
>>>from time importmktime,gmtime
>>>mktime(gmtime())
1460573789.0
六.sleep()
sleep函數用于將當前線程交出,要求它等待系統將其再次喚醒,如果寫程序只有一個線程,這實際上就會阻塞進程,什么也不做。
import time
def fucn():
time.sleep(5)
print"hello, world"
執行上面的代碼,將等待5秒鐘之后再輸出信息。