1. 程式人生 > >Python 常用函數Time

Python 常用函數Time

class ges 默認 一個 結構化 類型 %d .cn 夏令時

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

其中計算機認識的時間只能是‘時間戳‘格式,而程序員可處理的或者說人類能看懂的時間有: ‘格式化的時間字符串‘,‘結構化的時間‘ ,於是有了下圖的轉換關系

技術分享

#--------------------------按圖1轉換時間
# localtime([secs])
# 將一個時間戳轉換為當前時區的struct_time。secs參數未提供,則以當前時間為準。
time.localtime()
time.localtime(1473525444.037215)
# gmtime([secs]) 和localtime()方法類似,gmtime()方法是將一個時間戳轉換為UTC時區(0時區)的struct_time。
# mktime(t) : 將一個struct_time轉化為時間戳。
print(time.mktime(time.localtime()))#1473525749.0
# 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
# 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"。

技術分享

#--------------------------按圖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