Python 模組——time和datetime

來源:互聯網
上載者:User

標籤:pre   min   utc   mon   blog   mtime   run   部分   second   

時間相關的操作,時間有三種表示方式:

  • 時間戳記               1970年1月1日之後的秒,即:time.time()
  • 格式化的字串    2014-11-11 11:11,    即:time.strftime(‘%Y-%m-%d‘)
  • 結構化時間          元組包含了:年、日、星期等... time.struct_time    即:time.localtime()

time模組

import timeprint(time.time())   #輸出1495018452.927428print(time.ctime())  #輸出Wed May 17 18:54:48 2017 ,當前系統時間#struct_time對象print(time.gmtime()) #輸出time.struct_time(tm_year=2017, tm_mon=5, tm_mday=17, tm_hour=11, tm_min=0, tm_sec=56, tm_wday=2, tm_yday=137, tm_isdst=0)#注意:gmtime的時間是utc時間,即格林威治時間。加8之後才是北京時間(東八區)。localtime是本時區時間。print(time.localtime()) #輸出time.struct_time(tm_year=2017, tm_mon=5, tm_mday=17, tm_hour=19, tm_min=11, tm_sec=28, tm_wday=2, tm_yday=137, tm_isdst=0)time_obj = time.gmtime()print("{0}-{1}-{2}".format(time_obj.tm_year, time_obj.tm_mon, time_obj.tm_mday))print(time.mktime(time.localtime()))  #struct_time對象轉為時間戳記time.sleep(3)   #程式延遲3秒,再往後繼續執行print(time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime()))  #將struct_time格式轉成指定的字串格式print(time.strptime("2010-5-18 15:06", "%Y-%m-%d %H:%M"))    #將字串格式轉化成struct_time格式

  

datetime模組

import datetimeimport timeprint(datetime.date.today()) #輸出2017-05-17print(datetime.date.fromtimestamp(time.time()))  #輸出2017-05-17,將時間戳記轉換為日期格式current_time =datetime.datetime.now()print(current_time)    #輸出2017-05-17 22:03:40.630623print(current_time.timetuple())  #返回strunt_time格式print(current_time.replace(2015, 9, 10)) #替換目前時間中的指定部分print(datetime.datetime.now() + datetime.timedelta(days=10))  #比現在加10天print(datetime.datetime.now() + datetime.timedelta(days=-10)) #比現在減10天print(datetime.datetime.now() + datetime.timedelta(hours=10)) #比現在加10小時print(datetime.datetime.now() + datetime.timedelta(seconds=10)) #比現在加10秒print(datetime.datetime.strptime(‘21/11/06 16:03‘, ‘%d/%m/%y %H:%M‘))  #將字串轉為時間

  

Python 模組——time和datetime

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.