1. 程式人生 > >Python Time模塊

Python Time模塊

表示 浮點 sun .cn 5-0 浮點數 轉換 mat utc

一、定義

是Python處理有關時間的模塊

二、時間的三種格式

在Python中,通常有這幾種方式來表示時間:

  • 時間戳(timestamp):通常來說,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們運行“type(time.time())”,返回的是float類型。
  • 格式化的時間字符串(Format String)
  • 結構化的時間(struct_time):struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天,夏令時)
1 import time
2 #--------------------------我們先以當前時間為準,讓大家快速認識三種形式的時間
3 print(time.time()) # 時間戳:1487130156.419527 4 print(time.strftime("%Y-%m-%d %X")) #格式化的時間字符串:‘2017-02-15 11:40:53‘ 5 6 print(time.localtime()) #本地時區的struct_time 7 print(time.gmtime()) #UTC時區的struct_time

四、三種格式互轉

技術分享

 1 #--------------------------按圖1轉換時間
 2 # localtime([secs])
 3 # 將一個時間戳轉換為當前時區的struct_time。secs參數未提供,則以當前時間為準。
4 time.localtime() 5 time.localtime(1473525444.037215) 6 7 # gmtime([secs]) 和localtime()方法類似,gmtime()方法是將一個時間戳轉換為UTC時區(0時區)的struct_time。 8 9 # mktime(t) : 將一個struct_time轉化為時間戳。 10 print(time.mktime(time.localtime()))#1473525749.0 11 12 13 # strftime(format[, t]) : 把一個代表時間的元組或者struct_time(如由time.localtime()和
14 # time.gmtime()返回)轉化為格式化的時間字符串。如果t未指定,將傳入time.localtime()。如果元組中任何一個 15 # 元素越界,ValueError的錯誤將會被拋出。 16 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56 17 18 # time.strptime(string[, format]) 19 # 把一個格式化時間字符串轉化為struct_time。實際上它和strftime()是逆操作。 20 print(time.strptime(2011-05-05 16:37:06, %Y-%m-%d %X)) 21 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6, 22 # tm_wday=3, tm_yday=125, tm_isdst=-1) 23 #在這個函數中,format默認為:"%a %b %d %H:%M:%S %Y"。

技術分享

#--------------------------按圖2轉換時間
# asctime([t]) : 把一個表示時間的元組或者struct_time表示為這種形式:‘Sun Jun 20 23:21:05 1993‘。
# 如果沒有參數,將會將time.localtime()作為參數傳入。
print(time.asctime())#Sun Sep 11 00:43:43 2016

# 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

Python Time模塊