溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python中獲取當(dāng)前時間的操作步驟

發(fā)布時間:2020-08-07 09:36:18 來源:億速云 閱讀:170 作者:小新 欄目:編程語言

這篇文章主要介紹python中獲取當(dāng)前時間的操作步驟,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

python 如何獲取當(dāng)前系統(tǒng)的時間

1、導(dǎo)入包

import datetime

python學(xué)習(xí)網(wǎng),大量的免費(fèi)python視頻教程,歡迎在線學(xué)習(xí)!

2、獲取當(dāng)前的時間

curr_time = datetime.datetime.now()  # 2019-07-06 14:55:56.873893 <class 'datetime.datetime'>
curr_time.year  # 2019 <class 'int'>
curr_time.month  # 7 <class 'int'>
curr_time.day  # 6 <class 'int'>
curr_time.hour  # 14 <class 'int'>
curr_time.minute  # 55 <class 'int'>
curr_time.second  # 56 <class 'int'>
curr_time.date()  # 2019-07-06 <class 'datetime.date'>

3、格式化

通過datetime.datetime.now(),我們獲取到的時間格式為:2019-07-06 14:55:56.873893,類型:<class 'datetime.datetime'>

我們可以使用strftime()轉(zhuǎn)換成我們想要的格式。處理之后的返回的值為2019-07-06、07/06等目標(biāo)形式,類型為str

time_str = curr_time.strftime("%Y-%m-%d")  # 2019-07-06
time_str = curr_time.strftime("%m/%d")  # 07/06

4、類型轉(zhuǎn)換

時間一般通過:時間對象,時間字符串,時間戳表示

通過datetime獲取到的時間變量,類型為:datetime,那么datetime與str類型如何互相轉(zhuǎn)換呢?

datetime-->str
time_str = datetime.datetime.strftime(curr_time,'%Y-%m-%d %H:%M:%S')  # 2019-07-06 15:50:12
str-->datetime
time_str = '2019-07-06 15:59:58'
curr_time = datetime.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S')

以上是python中獲取當(dāng)前時間的操作步驟的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI