python學習(二十)時間模組方法

來源:互聯網
上載者:User

標籤:精確   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學習(二十)時間模組方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.