Python之時間:datetime模組

來源:互聯網
上載者:User

標籤:方法   python   nbsp   from   print   mtime   時間戳記   type   amp   

datetime在time基礎之上封裝了一些方法。但是time是經常使用的,datetime中的功能,time都能實現一、datetime的三個模組datetime.datedatetime.timedatetime.datetime 主要使用這個模組import datetime1、datetime.datetime.now() 擷取目前時間,datetime格式t1=datetime.datetime.now()print t1print t1.yearprint t1.day2017-05-28 11:32:21.853000(微妙:853000)201728 2、fromtimestamp 時間戳記轉換為datetimet2=time.time()dt=datetime.datetime.fromtimestamp(t2)print dtprint type(dt)結果:2017-05-28 11:34:20.725000<type ‘datetime.datetime‘> 3、strftime() 格式化輸出print datetime.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S‘) 4、replace() 把datetime中的某個值替換成需要的值t1=datetime.datetime.now()t2=t1.replace(month=4,hour=23)print t2結果:2017-04-28 23:50:10.855000t3=t1-t2print type(t3),t3結果:<type ‘datetime.timedelta‘> 29 days, 12:00:00 5、datetime.timedelta 解決一些時間差值問題class datetime.timedelta([days,[,hours[,minutes[,seconds[,microseconds]]]]])dt=datetime.timedelta(days=100)newTime=t1+dt 一百天之後的日期print newTime 結果:2017-09-05 11:54:52.479000dt1=datetime.timedelta(days=-100)newTime=t1+dt1 一百天之前的日期 6、total_seconds() 把時間轉換為秒seconds=datetime.timedelta(days=3).total_seconds() 把三天的時間轉換為秒print seconds結果:259200.0

Python之時間:datetime模組

聯繫我們

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