標籤:精確 unix min 時區時間 style strftime else 標準 列印
1、time 模組
時間戳記 從Unix元年到現在過了多少秒
格式化的時間
1)擷取目前時間戳
import timeprint(time.time())#擷取目前時間戳
2)在一段時間後輸出
import timetime.sleep(10)print(‘haha‘) #10秒後列印
3)擷取格式化好的時間
import timetoday=time.strftime(‘%Y-%m-%d %H:%M:%S‘) #擷取格式化好的時間print(today)
4)預設取得是標準時區的時間
import timeprint(time.gmtime())
5)擷取當前時區時間
import timeprint(time.localtime()) #取當前時區的時間
6)時間戳記轉換為時間元組,再將時間元群組轉換為格式化時間
import times=time.localtime(1514198608) #將時間戳記轉換為時間元組print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,s)) #再將時間元群組轉換為格式化時間
7)預設返回當前格式化好的時間,如果傳入了時間戳記,把時間戳記轉換成格式化好的時間並返回
import time
def timestamp_to_fomat(timestamp=None,format=‘%Y-%m-%d %H:%M:%S‘): if timestamp: time_tuple=time.localtime(timestamp) res=time.strftime(format,time_tuple) else: res=time.strftime(format) return resprint(timestamp_to_fomat())print(timestamp_to_fomat(1514198608))
8)把格式化好的時間轉換為時間元組,再把時間元群組轉換為時間戳記
import timetp=time.strptime(‘2018-4-21‘,‘%Y-%m-%d‘)#把格式化好的時間轉換成時間元組print(time.mktime(tp)) #把時間元群組轉換成時間戳記
9)函數未傳參數,返回目前時間的時間戳記,傳入參數則返回參數的時間戳記
import timedef strTimestamp(str=None,format=‘%Y%m%d%H%M%S‘): if str: tp=time.strptime(str,format) #轉換成時間元組 res=time.mktime(tp)#再轉換成時間戳記 else: res=time.time() #預設取目前時間的時間戳記 return int(res)print(strTimestamp())print(strTimestamp(‘20181229183859‘))print(strTimestamp(‘2018-12-29‘,‘%Y-%m-%d‘))
2、datetime模組1)擷取目前時間
import datetimeprint(datetime.datetime.today()) #擷取目前時間
2)擷取當天時間,精確到天
import datetimeprint(datetime.date.today()) #精確到天
3)擷取幾天后的時間
import datetimeres=datetime.date.today()+datetime.timedelta(days=5) #擷取到5天后的時間print(res) #也可以寫minutes,weeks,seconds 時間
4)擷取到幾天前的時間
import datetimeres=datetime.date.today()+datetime.timedelta(days=-5) #擷取到5天前的時間print(res)
5)擷取幾天前的時間(輸出格式自訂)
import datetimeres=datetime.date.today()+datetime.timedelta(days=-5) #擷取到5天前的時間print(res.strftime(‘%Y%m%d‘))
python學習(二十)時間模組方法