時間相關模塊
time模塊
時間表示方式
- 時間戳:表示的是從1970年1月1日00:00:00開始按秒計算的偏移量
- UTC時間:世界協調時
- struct_time:九元組時間(年,月,日,時,分,秒,一週中的第幾天,一年中的第幾天,是否使用DST夏季節約時間)
>>> import time
>>> time.time() # 當前時間的時間戳
1587432752.0444653
>>> time.ctime() # 當前UTC時間的字符串形式
'Tue Apr 21 09:33:08 2020'
>>> t = time.localtime() # 當前時間的九元組時間
>>> t
time.struct_time(tm_year=2020, tm_mon=4, tm_mday=21, tm_hour=9, tm_min=34, tm_sec=29, tm_wday=1, tm_yday=112, tm_isdst=0)
>>> t.tm_yday # 今天是一年中的第幾天
112
>>> t.tm_wday # 今天是一週中的第幾天,0表示週一
1
>>> time.sleep(3)
# 將當前時間轉成指定的字符串
>>> time.strftime('%Y-%m-%d %a %A %H:%M:%S')
'2020-04-21 Tue Tuesday 09:52:19'
# 將時間字符串轉換成9元組時間
>>> t1 = time.strptime('2021-5-1 9:20:30', '%Y-%m-%d %H:%M:%S')
>>> t1
time.struct_time(tm_year=2021, tm_mon=5, tm_mday=1, tm_hour=9, tm_min=20, tm_sec=30, tm_wday=5, tm_yday=121, tm_isdst=-1)
>>> t2 = time.strptime('2020-5-1 9:20:30', '%Y-%m-%d %H:%M:%S')
>>> t1 > t2
True
案例1:測試計算機從1加到一千萬的計算時間
import time
date1 = time.time()
result = 0
for i in range(1,10000001):
result += i
date2 = time.time()
data3 = date2 - date1
print(data3)
測試運行:
[root@python day6]# python3 lianxi.py
1.595163106918335
案例2:取出指定時間段的日誌
[root@python ~]# cat log.txt
2019-05-15 08:10:01 aaaa
2019-05-15 08:32:00 bbbb
2019-05-15 09:01:02 cccc
2019-05-15 09:28:23 dddd
2019-05-15 10:42:58 eeee
2019-05-15 11:08:00 ffff
2019-05-15 12:35:03 gggg
2019-05-15 13:13:24 hhhh
import time
t9 = time.strptime('2019-05-15 09:00:00','%Y-%m-%d %H:%M:%S')定義啓始時間,將時間轉換爲固定格式
t12 = time.strptime('2019-05-15 11:00:00','%Y-%m-%d %H:%M:%S')定義結束時間
with open('/root/log.txt') as fobj:
for line in fobj:
t = time.strptime(line[:19],'%Y-%m-%d %H:%M:%S')將每一行時間取出轉換爲格式爲'%Y-%m-%d %H:%M:%S'
if t > t12:
break
if t >= t9:
print(line,end='')
datetime模塊
>>> from datetime import datetime
>>> t = datetime.now()
>>> t # 返回當前時間的(年,月,日,時,分,秒,毫秒)
datetime.datetime(2020, 4, 21, 10, 41, 23, 617507)
>>> t.year, t.month, t.day
(2020, 4, 21)
>>> t.hour, t.minute, t.second, t.microsecond(毫秒)
(10, 41, 23, 617507)
# 將datetime對象轉成指定字符串
>>> t.strftime('%Y/%m/%d')
'2020/04/21'
# 將字符串轉爲datetime對象
>>> datetime.strptime('2020-4-21 10:50:00', '%Y-%m-%d %H:%M:%S')
# 計算時間差額
>>> from datetime import datetime, timedelta
>>> days = timedelta(days=100, hours=1)
>>> t = datetime.now()
>>> t
datetime.datetime(2020, 4, 21, 10, 52, 50, 982365)
>>> t - days # 100天1小時之前的時間
datetime.datetime(2020, 1, 12, 9, 52, 50, 982365)
>>> t + days # 100天1小時之後的時間
datetime.datetime(2020, 7, 30, 11, 52, 50, 982365)
異常
- 當程序運行時,因爲各種各樣的原因出錯了,那麼它將崩潰,終止執行,在屏幕上拋出異常
- 異常處理就是在代碼中提前給出錯誤解決方案。當程序遇到問題時,要執行哪些代碼進行補救
- 異常捕獲語法
try:
有可能發生異常的語句塊
except 異常1:
異常1發生時,執行的語句塊
except (異常2, 異常3):
異常2或異常3發生時,執行的語句塊
except (異常4, 異常5) as e: # 將異常保存到變量e中
異常4或異常5發生時,執行的語句塊
else:
異常不發生才執行的語句塊
finally:
不管異常是否發生,都要執行的語句塊
案例3: 寫個任意腳本練習異常處理
try:
n = int(input('數字:'))
result = 100 / n
print(result)
print('Done')
except ValueError: #無效的值
print('無效的值')
except EOFError: #讓用戶輸入的時候他按了ctrl + d 就會報 EOFError
print('\nBye Bye')
except KeyboardInterrupt:#讓用戶輸入的時候他按了ctrl + c 就會報KeyboardInterrupt
print('\nBye Bye')
except ZeroDivisionError: #0不能當被除數
print('無效的值')
案例4,優化案例3
try:
n = int(input('number:'))
result = 100 / n
print(result)
except (KeyboardInterrupt,EOFError):
print('\n Bye Bye')
exit() #程序遇到exit()函數將結束,不再向下執行
except (ZeroDivisionError,ValueError) as a:
print('無效的數字',a)
else:
print(result) #不出現異常才執行的語句塊
finally:
print('異常語句結束') #不管異常是否發生,都要執行的語句塊
print('Done')
主動觸發異常
- 使用raise主動觸發指定的異常
- assert觸發AssersionError異常
案例5 raise指定異常和斷言異常的使用
def get_info(name,age):
if not 0 < age < 119: 如果年齡大與119就報錯
raise ValueError('年齡超過範圍') raise主動觸發指定的異常
print('%s is %s years old' %(name,age))
def get_info2(name,age):
assert 0 < age < 120,'你活不到那麼大歲數吧' 斷言異常,如果判斷錯誤就會觸發異常
print('%s is %s years old' % (name, age))
if __name__ == '__main__':
get_info('kenji', 20)
get_info2('kenji',130)
os模塊
- 經常與shutil一起使用
- os模塊是python訪問文件系統的主要模塊
>>> import os
>>> os.getcwd() # pwd
'/root/nsd2019/nsd1911/py02/day01'
>>> os.listdir() # ls
>>> os.listdir('/tmp') # ls /tmp
>>> os.mkdir('/tmp/demo') # mkdir /tmp/demo
>>> os.mkdir('/tmp/nsd1911/mytest') # 報錯,不能遞歸創建目錄
>>> os.makedirs('/tmp/nsd1911/mytest') #mkdir -p /tmp/demo
>>> os.chdir('/tmp/demo')
>>> os.getcwd()
'/tmp/demo'
>>> import shutil
>>> shutil.copy('/etc/hosts', 'hosts')
>>> shutil.copytree('/etc/security', 'security')
# ln -s /etc/passwd mima
>>> os.symlink('/etc/passwd', 'mima')
>>> os.listdir()
['hosts', 'security', 'mima']
>>> os.environ # 環境變量
>>> os.environ['HOME']
'/root'
>>> os.environ['PATH']
'/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/root/bin:/root/bin'
>>> os.remove('mima') # rm mima
>>> os.rmdir('/tmp/nsd1911/mytest') # 刪除空目錄
>>> os.stat('/etc/hosts') # stat /etc/hosts
>>> os.chmod('/tmp/demo/hosts', 0o600) # 權限是8進制數字
>>> os.chmod('/tmp/demo/hosts', 420) # chmod 644
>>> os.path.abspath('hosts') # 返回絕對路徑
>>> os.path.basename('/var/tmp/abc.txt')
'abc.txt'
>>> os.path.dirname('/var/tmp/abc.txt')
'/var/tmp'
>>> os.path.split('/var/tmp/abc.txt')
('/var/tmp', 'abc.txt')
>>> os.path.join('/var/tmp', 'abc.txt') # 拼接路徑
'/var/tmp/abc.txt'
>>> os.path.isabs('/var/abc/xyz/') # 是絕對路嗎?
True
>>> os.path.isdir('/etc') # 存在並且是目錄嗎?
True
>>> os.path.isfile('/etc') # 存在並且是文件嗎?
False
>>> os.path.islink('/etc/grub2.cfg') # 存在並且是軟鏈接嗎?
True
>>> os.path.ismount('/') # 存在並且是掛載點嗎?
True
>>> os.path.exists('/etc/passwd') # 存在嗎?
True
os.walk()函數
[root@localhost nsd2019]# mkdir -p /tmp/mydemo/{aaa/bbb,ccc,ddd}
[root@localhost nsd2019]# ls /tmp/mydemo/
aaa ccc ddd
[root@localhost nsd2019]# ls /tmp/mydemo/aaa/
bbb
[root@localhost nsd2019]# touch /tmp/mydemo/file{01,02}
[root@localhost nsd2019]# touch /tmp/mydemo/aaa/file{03,04}
[root@localhost nsd2019]# touch /tmp/mydemo/aaa/bbb/file{05,06}
[root@localhost nsd2019]# touch /tmp/mydemo/ccc/file{07,08}
[root@localhost nsd2019]# touch /tmp/mydemo/ddd/file{09,10}
[root@localhost nsd2019]# ls -R /tmp/mydemo/
/tmp/mydemo/:
aaa ccc ddd file01 file02
/tmp/mydemo/aaa:
bbb file03 file04
/tmp/mydemo/aaa/bbb:
file05 file06
/tmp/mydemo/ccc:
file07 file08
/tmp/mydemo/ddd:
file09 file10
>>> import pprint
>>> flist = list(os.walk('/tmp/mydemo'))
>>> pprint.pprint(flist)
[('/tmp/mydemo', ['aaa', 'ccc', 'ddd'], ['file01', 'file02']),
('/tmp/mydemo/aaa', ['bbb'], ['file03', 'file04']),
('/tmp/mydemo/aaa/bbb', [], ['file05', 'file06']),
('/tmp/mydemo/ccc', [], ['file07', 'file08']),
('/tmp/mydemo/ddd', [], ['file09', 'file10'])]
# flist列表有5項,每項結構相同
>>> len(flist)
5
# 列表由元組構成
>>> flist[0]
('/tmp/mydemo', ['aaa', 'ccc', 'ddd'], ['file01', 'file02'])
# 元組又由3項構成
>>> len(flist[0])
3
# 元組中的三項是: (路徑字符串,路徑下目錄列表,路徑下文件列表)
>>> for data in os.walk('/tmp/mydemo'):
... print(data)
>>> for lujing, mulu, wenjian in os.walk('/tmp/mydemo'):
... print("%s:\n%s%s" % (lujing, mulu, wenjian))
... print()
>>> for path, folders, files in os.walk('/tmp/mydemo'):
... print('%s:' % path)
... for mulu in folders:
... print(mulu, end='\t')
... for file in files:
... print(file, end='\t')
... print('\n')
pickle模塊
- 將各種各樣的數據存入到文件中,並且可以將它們無損地取出
# 文件本身的寫入方法,只能把字符串寫到文件中
# 從文件中取出的也是字符串,不是列表
>>> shopping_list = ['apple', 'bananer', 'pear', 'peach']
>>> f = open('/tmp/shop.txt', 'w')
>>> f.write(shopping_list) # 報錯,只能寫入字符串,列表不行
>>> f.write(str(shopping_list))
>>> f.close()
[root@localhost day01]# cat /tmp/shop.txt
['apple', 'bananer', 'pear', 'peach']
# 使用pickle將列表存入文件
>>> import pickle
>>> f = open('/tmp/shop.data', 'wb')
>>> pickle.dump(shopping_list, f)
>>> f.close()
# 將列表從文件中取出
>>> with open('/tmp/shop.data', 'rb') as fobj:
... l1 = pickle.load(fobj)
>>> type(l1)
<class 'list'>
>>> l1
['apple', 'bananer', 'pear', 'peach']
>>> len(l1)
4
>>> l1[0]
'apple'