在python中與事件處理相關的模組有:
time datetime calendar ,這裡先講解time模組
1.time
模組的引入用import time
(1) time.time() 返回當前時間的時間戳(1970紀元後經過的浮點秒數) 返回結果資料型別是float
執行結果如下:import time
temp=time.time()
print(temp)
1530102947.1895583
(2) time.ctime() 獲取當前日期時間 返回結果資料型別是字串
執行結果是:import time
temp=time.ctime()
print(temp)
wed jun 27 20:38:57 2018
(3) time.localtime() 將乙個時間戳轉化為當地時期的時間
執行結果是:import time
temp=time.localtime(time.time())
print(temp)
time.struct_time(tm_year=2018, tm_mon=6, tm_mday=27, tm_hour=20, tm_min=46, tm_sec=34, tm_wday=2, tm_yday=178, tm_isdst=0)
(4) time.sleep( )執行緒推遲指定的時間
三秒後執行語句,執行結果為:import time
time.sleep(3)
print("today is a good day")
today is a good day
(5) time.asctime( )接受時間元組 返回乙個可讀形式的字串
返回結果是:import time
tuplea=(2018,1,2,3,4,5,1,22,0)
a=time.asctime(tuplea)
print(a)
print(a[-1])
(6) time.mktime( )接受時間元組並返回時間戳tue jan 2 03:04:05 2018
8
執行結果是import time
tuplea=(2018,1,2,3,4,5,1,22,0)
temp=time.mktime(tuplea)
print(temp)
1514833445.0
(7)time.strftime( ) 將時間時間元組轉化為字串
結果是:tims=(2018,5,17,0,0,0,0,0,0)
b=time.strftime("%y %m %d ",tims).format(x="年",y="月",z="日")
print(b)
2023年 05月 17日
(8) time.strptime( ) 將字串或者struct_time轉化轉化為時間元組
執行結果是:stra="2023年5月15日"
a=time.strptime(stra,"%y年%m月%d日")
print(a)
print(type(a))
struct_time是一種資料型別,如上執行結果所示,time.gmtime()、time.localtime()(將乙個時間戳轉化為struct_time)time.struct_time(tm_year=2018, tm_mon=5, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=135, tm_isdst=-1)
執行結果是:temp=time.gmtime(time.time())
b=time.strftime("%y %m %d %h %m %s",temp).format(x="年",y="月",z="日",a="時",b="分",c="秒")
print(b)
2023年 06月 27日 13時 31分 56秒
time.localtime() 將乙個時間戳轉化為struct_time
執行結果(tm_isdst始終是零):temp=time.localtime(time.time())
print(temp)
b=time.strftime("%y %m %d %h %m %s",temp).format(x="年",y="月",z="日",a="時",b="分",c="秒")
print(b)
(9) time.clock( )計算程式執行的時間time.struct_time(tm_year=2018, tm_mon=6, tm_mday=27, tm_hour=21, tm_min=48, tm_sec=33, tm_wday=2, tm_yday=178, tm_isdst=0)
2023年 06月 27日 21時 48分 33秒
執行結果(列印的數字沒有展示出):print(time.clock())
for i in range(1000000):
print(i)
print("結束後")
print(time.clock())
2. 時間元組結束後
4.2173296979444554
python用乙個元組裝起來的九組數稱之為時間元組,比如
t=(2018,1,2,3,4,5,1,23,0)
分別表示年(四位數),月(1-12),日(1-31),時(0-23),分(0-59),秒(0-59),一周第幾日(0-6 0表示週日),一年第幾日(1-366),夏令時(是否是夏令時,預設為-1).
3.日期格式化
time.strftime( ) 把乙個代表時間的元組為格式化的字串.
python中常用的時間日期格式化符號:
%y 兩位數年份表示(00-99)
%y 四位數的年份表示(0000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%h 24小時制小時數(0-23)
%i 12小時制小時數(01-12)
%m 分鐘數(00-59)
%s 秒數(00-59)
time模組 日期轉換
一種獲取當前時間,以及時間格式化的模組 time模組在python原生安裝中就存在,直接使用即可,無需額外的安裝操作 coding utf 8 import time import locale 設定本地語言型別為中文 locale.setlocale locale.lc ctype,chinese...
Python日期格式化 time模組
time.struct time tm year 2019 tm mon 5,tm mday 17,tm hour 14,tm min 26,tm sec 53,tm wday 4,tm yday 137,tm isdst 0 time.struct time tm year 2019 tm mon...
python 利用time模組獲取當前 日期時間
取得時間相關的資訊的話,要用到python time模組,python time模組裡面有很多非常好用的功能,你可以去官方 文件了解下,要取的當前時間的話,要取得當前時間的時間戳,時間戳好像是1970年到現在時間相隔的時間。你可以試下下面的方式來取得當前時間的時間戳 import time prin...