天天看點

python日期與時間

1.介紹

  Python 提供了一個 time 和 calendar 子產品可以用于格式化日期和時間。

  時間間隔是以秒為機關的浮點小數。

  每個時間戳都以自從1970年1月1日午夜(曆元)經過了多長時間來表示。

一:擷取時間戳

1.程式

1 # -*- coding: UTF-8 -*-
2 
3 import time;  # 引入time子產品
4 
5 ticks = time.time()
6 print "目前時間戳為:", ticks      

二:擷取目前時間

1.時間元祖

  Python函數用一個元組裝起來的9組數字處理時間

  

python日期與時間

2.程式

  從傳回浮點數的時間戳方式向時間元組轉換,隻要将浮點數傳遞給如localtime之類的函數。

1 # -*- coding: UTF-8 -*-
2 import time
3 
4 localtime = time.localtime(time.time())
5 print "本地時間為 :", localtime      

3.效果

python日期與時間

三:擷取格式化的時間      

1 # -*- coding: UTF-8 -*-
2 import time
3 
4 localtime = time.asctime( time.localtime(time.time()) )
5 print "本地時間為 :", localtime      

2.效果

python日期與時間

--------=====================================================================================日期=====================

四:格式化日期

  我們可以使用 time 子產品的 strftime 方法來格式化日期

2.格式化符号

python日期與時間

 3.程式

1 # -*- coding: UTF-8 -*-
 2 import time
 3 
 4 # 格式化成2016-03-20 11:45:39形式
 5 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
 6 
 7 # 格式化成Sat Mar 28 22:24:24 2016形式
 8 print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
 9 
10 # 将格式字元串轉換為時間戳
11 a = "Sat Mar 28 22:24:24 2016"
12 print time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y"))
13 
14 print time.localtime()      

4.效果

python日期與時間

五:擷取月曆

  Calendar子產品有很廣泛的方法用來處理年曆和月曆,例如列印某月的月曆

1 # -*- coding: UTF-8 -*-
2 import calendar
3 
4 cal = calendar.month(2016, 1)
5 print "以下輸出2016年1月份的月曆:"
6 print cal;      
python日期與時間

六:Time子產品

1.函數

python日期與時間

七:Calendar子產品

python日期與時間
  • datetime子產品
  • pytz子產品
  • dateutil子產品

繼續閱讀