詳解python中的time和datetime的常用方法
一、time的常用方法:
import time,datetime # 時間有三種展現(xiàn)方式:時間戳,時間元組,格式化的時間 print(time.time())#當前時間戳 print(int(time.time())) print(time.strftime('%Y-%m-%d %H:%M:%S'))#格式化的時間 print(time.strftime('%Y-%m-%d')) print(time.strftime('%H:%M:%S')) print(time.gmtime())#獲取標準時區(qū)的時間元組,如果傳入了時間戳,就是把時間戳轉換成時間元組 print(time.gmtime(1516194265))
執(zhí)行結果:
1516197631.0563018
1516197631
2018-01-17 22:00:31
2018-01-17
22:00:31
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=17, tm_hour=14, tm_min=0, tm_sec=31, tm_wday=2, tm_yday=17, tm_isdst=0)
time.struct_time(tm_year=2018, tm_mon=1, tm_mday=17, tm_hour=13, tm_min=4, tm_sec=25, tm_wday=2, tm_yday=17, tm_isdst=0)
二、 datetime常用方法:
# 使用datetime和time獲取當前時間 now1 = datetime.datetime.now() now2=time.strftime('%Y-%m-%d %H:%M:%S') print(now1) print(now2) now = datetime.datetime.now() d1 = now - datetime.timedelta(hours=1)#獲取前一小時 d2 = now - datetime.timedelta(days=1)#獲取前一天 print(now) print(d1)
執(zhí)行結果:
2018-01-17 22:03:04.686923
2018-01-17 22:03:04
2018-01-17 22:03:04.687486
2018-01-17 21:03:04.687486
三、使用datetime獲取代碼執(zhí)行的時長
# 使用時間戳獲取代碼執(zhí)行時間 s_time = time.time() for i in range(0,10): time.sleep(1) e_time=time.time() print('代碼運行時間是:',e_time - s_time)
執(zhí)行結果:
代碼運行時間是: 10.003105163574219
四、時間戳和字符串的互相轉化
# 字符串格式化時間轉換時間戳 str_time = '2018-1-17' print(time.mktime(time.strptime(str_time,'%Y-%m-%d'))) # 時間戳轉換成格式化的時間字符串 gsh_time= time.time() print(time.strftime('%Y-%m-%d',time.localtime(gsh_time))) # datetime對象轉換成時間戳 dt = datetime.datetime.now() print(time.mktime(dt.timetuple())) # 時間戳轉換成datetime對象 sjc_time = time.time() print(datetime.datetime.fromtimestamp(sjc_time))
執(zhí)行結果:
1516118400.0
2018-01-17
1516198008.0
2018-01-17 22:06:48.944055
總結
以上所述是小編給大家介紹的python中的time和datetime的常用方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
- python datetime時間格式的相互轉換問題
- python3中datetime庫,time庫以及pandas中的時間函數(shù)區(qū)別與詳解
- Python 日期時間datetime 加一天,減一天,加減一小時一分鐘,加減一年
- Python datetime 格式化 明天,昨天實例
- python3實現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)
- python GUI庫圖形界面開發(fā)之PyQt5日期時間控件QDateTimeEdit詳細使用方法與實例
- python datetime中strptime用法詳解
- python中時間轉換datetime和pd.to_datetime詳析
- 詳解python datetime模塊
相關文章
Python cookbook(數(shù)據(jù)結構與算法)找出序列中出現(xiàn)次數(shù)最多的元素算法示例
這篇文章主要介紹了Python cookbook(數(shù)據(jù)結構與算法)找出序列中出現(xiàn)次數(shù)最多的元素算法,涉及Python collections模塊中的Counter類相關使用技巧與操作注意事項,需要的朋友可以參考下2018-03-03Python簡單實現(xiàn)兩個任意字符串乘積的方法示例
這篇文章主要介紹了Python簡單實現(xiàn)兩個任意字符串乘積的方法,結合實例形式分析了Python針對字符串、列表的切片、轉換、遍歷等相關操作技巧,需要的朋友可以參考下2018-04-04springboot配置文件抽離 git管理統(tǒng) 配置中心詳解
在本篇文章里小編給大家整理的是關于springboot配置文件抽離 git管理統(tǒng) 配置中心的相關知識點內容,有需要的朋友們可以學習下。2019-09-09