python擷取目前時間的教程

來源:互聯網
上載者:User

介紹完電腦時間的背景,下面就要來乾貨了,我把用python擷取系統時間常用的例子匯總了下,方便小夥伴們快速上手和查詢,並且支援日期的常見格式,我們先說如何用time模組來時間我們要的時間:

>>> import time
>>> time.time()
1469101837.655935

time.time()函數就是返回的UTC時間,是從1970.1.1到現在的秒數。

>>> time.ctime(1469101837.655935)
'Thu Jul 21 19:50:37 2016'

time.ctime()函數接收一個以秒為單位的實際,然後轉換成本地時間的字串表示。

如果我們想格式化時間格式的輸出,可以用strftime()函數,這樣能把我們的時間格式變為我們想要的格式:


>>> from time import strftime,gmtime
>>> strftime("%m/%d/%Y %H:%M")
'07/21/2016 19:57'
>>> time.strftime("%Y%m%d")
'20160721'
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2016-07-21 11:47:51'

在python中,除了time模組外還有datetime模組,也可以方便的操作時間,比如用datetime模組來顯示目前時間:

>>> from datetime import datetime
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2016-07-21 19:49:15'
>>> datetime.now().isoformat()
'2016-07-21T19:56:46.744893'
>>> str(datetime.now())
'2016-07-21 19:48:37.436886'

Unix timestamp:是從1970年1月1日(UTC/GMT的午夜)開始所經過的秒數,不考慮閏秒

import datetime
import time
print time.mktime(datetime.datetime.now().timetuple())

輸出為:

1431674373.0

在指令碼中,這2個模組都比較常用,比如做檔案備份時要加的時間戳記變數,對老舊檔案刪除操作的時間變數等,大家可以通過上面的例子進行自己修改來得到想要的格式,如果只需要時間的某部分,可以用split()函數分割,通過切片獲得想要的內容,這篇就到這裡,有問題歡迎留言。

聯繫我們

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