Python 日期和時間

獲取當前時間戳

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import time;  # 引入time模塊
 
ticks = time.time()
print "當前時間戳爲:", ticks
當前時間戳爲: 1459994552.51

 

獲取當前時間

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import time
 
localtime = time.localtime(time.time())
print "本地時間爲 :", localtime
本地時間爲 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)

 

獲取格式化的時間

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import time
 
localtime = time.asctime( time.localtime(time.time()) )
print "本地時間爲 :", localtime
本地時間爲 : Thu Apr  7 10:05:21 2016

 

格式化日期

我們可以使用 time 模塊的 strftime 方法來格式化日期,:

time.strftime(format[, t])
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import time
 
# 格式化成2016-03-20 11:45:39形式
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
 
# 格式化成Sat Mar 28 22:24:24 2016形式
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 
  
# 將格式字符串轉換爲時間戳
a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
2016-04-07 10:25:09
Thu Apr 07 10:25:09 2016
1459175064.0

Python中時間日期格式化符號:

%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12)
%M 分鐘數(00=59)
%S 秒(00-59)
%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.的等價符
%U 一年中的星期數(00-53)星期天爲星期的開始
%w 星期(0-6),星期天爲星期的開始
%W 一年中的星期數(00-53)星期一爲星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身

 

獲取某月日曆

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import calendar
 
cal = calendar.month(2016, 1)
print "以下輸出2016年1月份的日曆:"
print cal
以下輸出2016年1月份的日曆:
    January 2016
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章