python 如何获取当前系统的时间
生活随笔
收集整理的這篇文章主要介紹了
python 如何获取当前系统的时间
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.導(dǎo)入包 import datetime
2.獲取當(dāng)前的時(shí)間
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(),我們獲取到的時(shí)間格式為: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)換
時(shí)間一般通過:時(shí)間對(duì)象,時(shí)間字符串,時(shí)間戳表示
通過datetime獲取到的時(shí)間變量,類型為: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')
總結(jié)
以上是生活随笔為你收集整理的python 如何获取当前系统的时间的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 语义网所谓的“本体”的具体例子是什么?人
- 下一篇: 存在量词后必须用合取式?-数学