time模塊

三種時間表示

在Python中,一般有這幾種方式來表示時間:函數

  • 時間戳(timestamp) :         一般來講,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。咱們運行「type(time.time())」,返回的是float類型。
  • 格式化的時間字符串
  • 元組(struct_time)   :         struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天,夏令時)
import time
 
# 1 time() :返回當前時間的時間戳
time.time()  #1473525444.037215
 
#----------------------------------------------------------
 
# 2 localtime([secs])
# 將一個時間戳轉換爲當前時區的struct_time。secs參數未提供,則以當前時間爲準。
time.localtime() #time.struct_time(tm_year=2016, tm_mon=9, tm_mday=11, tm_hour=0,
# tm_min=38, tm_sec=39, tm_wday=6, tm_yday=255, tm_isdst=0)
time.localtime(1473525444.037215)
 
#----------------------------------------------------------
 
# 3 gmtime([secs]) 和localtime()方法相似,gmtime()方法是將一個時間戳轉換爲UTC時區(0時區)的struct_time。
 
#----------------------------------------------------------
 
# 4 mktime(t) : 將一個struct_time轉化爲時間戳。
print(time.mktime(time.localtime()))#1473525749.0
 
#----------------------------------------------------------
 
# 5 asctime([t]) : 把一個表示時間的元組或者struct_time表示爲這種形式:'Sun Jun 20 23:21:05 1993'。
# 若是沒有參數,將會將time.localtime()做爲參數傳入。
print(time.asctime())#Sun Sep 11 00:43:43 2016
 
#----------------------------------------------------------
 
# 6 ctime([secs]) : 把一個時間戳(按秒計算的浮點數)轉化爲time.asctime()的形式。若是參數未給或者爲
# None的時候,將會默認time.time()爲參數。它的做用至關於time.asctime(time.localtime(secs))。
print(time.ctime())  # Sun Sep 11 00:46:38 2016
 
print(time.ctime(time.time()))  # Sun Sep 11 00:46:38 2016
 
# 7 strftime(format[, t]) : 把一個表明時間的元組或者struct_time(如由time.localtime()和
# time.gmtime()返回)轉化爲格式化的時間字符串。若是t未指定,將傳入time.localtime()。若是元組中任何一個
# 元素越界,ValueError的錯誤將會被拋出。
print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
 
# 8 time.strptime(string[, format])
# 把一個格式化時間字符串轉化爲struct_time。實際上它和strftime()是逆操做。
print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
 
#time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
#  tm_wday=3, tm_yday=125, tm_isdst=-1)
 
#在這個函數中,format默認爲:"%a %b %d %H:%M:%S %Y"。
 
 
# 9 sleep(secs)
# 線程推遲指定的時間運行,單位爲秒。
 
# 10 clock()
# 這個須要注意,在不一樣的系統上含義不一樣。在UNIX系統上,它返回的是「進程時間」,它是用秒錶示的浮點數(時間戳)。
# 而在WINDOWS中,第一次調用,返回的是進程運行的實際時間。而第二次以後的調用是自第一次調用之後到如今的運行
# 時間,即兩次時間差。

          

help(time)
help(time.asctime)
相關文章
相關標籤/搜索