標籤:timestamp utc 本地 表示 元組 erro replace 第幾天 info
在Python中,通常有這幾種方式來表示時間:
import time#--------------------------我們先以目前時間為準,讓大家快速認識三種形式的時間print(time.time()) # 時間戳記:1487130156.419527print(time.strftime("%Y-%m-%d %X")) #格式化的時間字串:‘2017-02-15 11:40:53‘print(time.localtime()) #本地時區的struct_timeprint(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 2016print(time.ctime(time.time())) # Sun Sep 11 00:46:38 2016
#時間加減import datetime# print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925#print(datetime.date.fromtimestamp(time.time()) ) # 時間戳記直接轉成日期格式 2016-08-19# print(datetime.datetime.now() )# print(datetime.datetime.now() + datetime.timedelta(3)) #目前時間+3天# print(datetime.datetime.now() + datetime.timedelta(-3)) #目前時間-3天# print(datetime.datetime.now() + datetime.timedelta(hours=3)) #目前時間+3小時# print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #目前時間+30分## c_time = datetime.datetime.now()# print(c_time.replace(minute=3,hour=2)) #時間替換datetime模組
線程延遲使用方法:
# sleep(secs) # 線程延遲指定的時間運行,單位為秒。
Python之時間(time)模組