一、time與datetime模塊
==========time模塊==========
1、時間有三種格式(*****)
# 1、時間戳:秒數=>用于時間計算(得到的是浮點型,用于加減乘除運算) start=time.time() print(start,type(start)) #1596367382.30072 <class 'float'> # 2、格式化的字串=>用于顯示給人看(得到的是字串型別,可用于寫到檔案中) res=time.strftime("%Y-%m-%d %H:%S:%M %p") res=time.strftime("%Y-%m-%d %X") print(res,type(res)) #2020-08-02 19:23:02 <class 'str'> # 3、結構化的時間=>獲取時間的某一部分(以此可以按照當前的時間計算出另外一個時間) res = time.localtime() res1 = time.gmtime() #不同之處就是localtime按照東八區計時(中國時間),gmtime以國際標準計算時間,英國本初子午線劃分 print(res) #time.struct_time(tm_year=2020, tm_mon=8, tm_mday=2, tm_hour=19, tm_min=23, tm_sec=2, tm_wday=6, tm_yday=215, tm_isdst=0) print(res1) #time.struct_time(tm_year=2020, tm_mon=8, tm_mday=2, tm_hour=11, tm_min=23, tm_sec=2, tm_wday=6, tm_yday=215, tm_isdst=0) print(type(res)) #<class 'time.struct_time'> print(res.tm_year)#選出其中一個 這里選出的是年 #列印出 2020
2、時間格式轉換

# 2.1 時間戳---》格式化的字串 struct_time=time.localtime(3333.3) #time.localtime()不傳值默認就是time.time() res=time.strftime("%Y-%m",struct_time) print(res) #1970-01 # 2.2 格式化的字串---》時間戳 struct_time=time.strptime("2017-07-03 11:11:11","%Y-%m-%d %H:%M:%S") res=time.mktime(struct_time) print(res) #1499051471.0
3、

print(time.ctime(3333.3)) # Thu Jan 1 08:55:33 1970 #time.ctime()不傳值默認就是time.time() print(time.asctime(time.localtime(3333.3))) #Thu Jan 1 08:55:33 1970
4、time.sleep(3) #括號內傳秒
==========datetime模塊==========
import datetime res=datetime.datetime.now() print(res) #直接獲取當前時間 print(datetime.date.fromtimestamp(time.time())) #時間戳直接轉成日期格式 2020-08-02 print(datetime.datetime.fromtimestamp(time.time())) #2020-08-02 19:55:15.371285 #舉例:計算三天前/三天后 res=datetime.datetime.now() + datetime.timedelta(days=3) res=datetime.datetime.now() + datetime.timedelta(days=-3) print(res) #當前時間 res=datetime.datetime.now() print(res) #以當前時間為基準,把年/月/日等換掉 new_res=res.replace(year=1999,month=9) print(new_res) ------------------------------------------------------------------------------------------------- # print(datetime.datetime.now()) #回傳 2016-08-19 12:47:03.941925 #print(datetime.date.fromtimestamp(time.time()) ) # 時間戳直接轉成日期格式 2016-08-19 # print(datetime.datetime.now() ) # print(datetime.datetime.now() + datetime.timedelta(3)) #當前時間+3天 # print(datetime.datetime.now() + datetime.timedelta(-3)) #當前時間-3天 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當前時間+3小時 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當前時間+30分 # c_time = datetime.datetime.now() # print(c_time.replace(minute=3,hour=2)) #時間替換
二、random模塊
import random # print(random.random()) # print(random.randint(1,3)) # print(random.choice([1,'23',[4,5]])) # print(random.sample([1,'23',[4,5]],2)) # print(random.uniform(1,3)) # item=[1,3,5,7,9] # random.shuffle(item) # print(item) # 隨機驗證碼 # print(chr(65)) # print(chr(90)) def make_code(n=5): res = '' for i in range(n): s1 = str(random.randint(0, 9)) s2 = chr(random.randint(65, 90)) res += random.choice([s1, s2]) return res print(make_code(4))
三、os模塊
os.system沒有回傳值 res=os.system()#0代表命令運行正確,1代表命令運行錯誤
# import os # print(os.listdir(".")) # import os # cmd=input(r""" # Microsoft Windows [版本 10.0.17763.1339] # (c) 2018 Microsoft Corporation,保留所有權利, # # %s=====> """ %os.getcwd()) # res=os.system(cmd) # print('='*100) # print(res) import os # print(__file__) # print(os.path.abspath(__file__)) # res=os.path.split("D:/python全堆疊15期/day21/03 os模塊.py") # print(res) # print(os.path.basename("D:/python全堆疊15期/day21/03 os模塊.py")) # print(os.path.dirname("D:/python全堆疊15期/day21/03 os模塊.py")) # print(os.path.exists("D:/python全堆疊15期/day21/")) # print(os.path.isabs("D:/python全堆疊15期/day21/")) # print(os.path.isabs("/python全堆疊15期/day21/")) # print(os.path.isabs("python全堆疊15期/day21/")) # print(os.path.join("a",'b','D:\c','d.txt')) # print(os.path.dirname(os.path.dirname(__file__))) # res=os.path.join( # __file__, # "..", # ".." # ) # # print(os.path.normpath(res)) print(os.path.getsize(__file__))
os.getcwd() 獲取當前作業目錄,即當前python腳本作業的目錄路徑 os.chdir("dirname") 改變當前腳本作業目錄;相當于shell下cd os.curdir 回傳當前目錄: ('.') os.pardir 獲取當前目錄的父目錄字串名:('..') os.makedirs('dirname1/dirname2') 可生成多層遞回目錄 os.removedirs('dirname1') 若目錄為空,則洗掉,并遞回到上一級目錄,如若也為空,則洗掉,依此類推 os.mkdir('dirname') 生成單級目錄;相當于shell中mkdir dirname os.rmdir('dirname') 洗掉單級空目錄,若目錄不為空則無法洗掉,報錯;相當于shell中rmdir dirname os.listdir('dirname') 列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,并以串列方式列印 os.remove() 洗掉一個檔案 os.rename("oldname","newname") 重命名檔案/目錄 os.stat('path/filename') 獲取檔案/目錄資訊 os.sep 輸出作業系統特定的路徑分隔符,win下為"\\",Linux下為"/" os.linesep 輸出當前平臺使用的行終止符,win下為"\r\n",Linux下為"\n" os.pathsep 輸出用于分割檔案路徑的字串 win下為;,Linux下為: os.name 輸出字串指示當前使用平臺,win->'nt'; Linux->'posix' os.system("bash command") 運行shell命令,直接顯示 os.environ 獲取系統環境變數 os.path.abspath(path) 回傳path規范化的絕對路徑 os.path.split(path) 將path分割成目錄和檔案名二元組回傳 os.path.dirname(path) 回傳path的目錄,其實就是os.path.split(path)的第一個元素 os.path.basename(path) 回傳path最后的檔案名,如何path以/或\結尾,那么就會回傳空值,即os.path.split(path)的第二個元素 os.path.exists(path) 如果path存在,回傳True;如果path不存在,回傳False os.path.isabs(path) 如果path是絕對路徑,回傳True os.path.isfile(path) 如果path是一個存在的檔案,回傳True,否則回傳False os.path.isdir(path) 如果path是一個存在的目錄,則回傳True,否則回傳False os.path.join(path1[, path2[, ...]]) 將多個路徑組合后回傳,第一個絕對路徑之前的引數將被忽略 os.path.getatime(path) 回傳path所指向的檔案或者目錄的最后存取時間 os.path.getmtime(path) 回傳path所指向的檔案或者目錄的最后修改時間 os.path.getsize(path) 回傳path的大小
四、sys模塊
sys.path第一個 環境變數參照當前執行檔案(在包里就是被呼叫者),跟當前所在的檔案無關
匯入包就是在導init__.py,匯入模塊,出發init__.py的運行
包的使用者,處理環境變數,呼叫包,被倒入的包/模塊
絕對匯入(通用):以包的根目錄為起始點,開始匯入
相對匯入(簡單,只能在包里用):.當前檔案 ..上一級 ...上一級 但是不能超出包
import sys # sys.path # print(sys.argv) # src_file = input("源檔案路徑:").strip() # dst_file = input("目標檔案路徑:").strip() # src_file = sys.argv[1] # dst_file = sys.argv[2] # # with open(r"%s" %src_file,mode='rb') as f1,open(r"%s" %dst_file,mode='wb') as f2: # for line in f1: # f2.write(line)
列印進度條知識儲備:
# import time # print("[# ]",end='') # time.sleep(0.3) # print("\r[## ]",end='') # time.sleep(0.3) # print("\r[### ]",end='') # time.sleep(0.3) # print("\r[#### ]",end='') # print("[%-15s]" % "###",) # print("[%-15s]" % "####",) import time def progress(percent): if percent > 1: percent=1 print("\r[%-50s] %d%%" % ("#"*int(50*percent),int(100 * percent)),end='') total_size = 1025 recv_size = 0 while recv_size < total_size: # 每次下載1024 time.sleep(0.3) recv_size+=1024 percent = recv_size / total_size progress(percent)
列印進度條
列印效果:100.0% [====================>]
方式一:
列印效果:####################|100%
#列印效果 ####################|100% import time # 列印進度條 def progress_bar(new_size, sum_size): """根據每次輸入的大小判斷目前的百分比""" bar = int(new_size/sum_size * 100) bar_num = bar//5 print("\r%s|%s%%"%("#"*bar_num,bar),end="") for i in range(1,101): time.sleep(0.1) progress_bar(i,100)方式二:
五、configparser模塊
import subprocess # pwd ; sasdfasdf ;echo 123 obj = subprocess.Popen("diasfdafr", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) res1=obj.stdout.read() res2=obj.stderr.read() # print(res1.decode('gbk')) print(res2.decode('gbk'))
六、suprocess模塊
import subprocess 2 3 ''' 4 sh-3.2# ls /Users/egon/Desktop |grep txt$ 5 mysql.txt 6 tt.txt 7 事物.txt 8 ''' 9 10 res1=subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE) 11 res=subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout, 12 stdout=subprocess.PIPE) 13 14 print(res.stdout.read().decode('utf-8')) 15 16 17 #等同于上面,但是上面的優勢在于,一個資料流可以和另外一個資料流互動,可以通過爬蟲得到結果然后交給grep 18 res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE) 19 print(res1.stdout.read().decode('utf-8')) 20 21 22 #windows下: 23 # dir | findstr 'test*' 24 # dir | findstr 'txt$' 25 import subprocess 26 res1=subprocess.Popen(r'dir C:\Users\Administrator\PycharmProjects\test\函式備課',shell=True,stdout=subprocess.PIPE) 27 res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout, 28 stdout=subprocess.PIPE) 29 30 print(res.stdout.read().decode('gbk')) #subprocess使用當前系統默認編碼,得到結果為bytes型別,在windows下需要用gbk解碼
---21---
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/73437.html
標籤:Python
下一篇:145二叉樹的后序遍歷
