獲取當前時間


1.導入包   import datetime

2.獲取當前的時間

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()轉換成我們想要的格式。處理之后的返回的值為2019-07-06、07/06等目標形式,類型為str

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

4.類型轉換

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

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

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')

獲取指定時間
from datetime import date

date = date(1991,1,1)  # 1991-01-01

from datetime import datetime

date_time = datetime(1992,1,1,12,23,12) # 1992-01-01 12:23:12

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM