1. 程式人生 > >Python--模塊之time、random、os、hashlib

Python--模塊之time、random、os、hashlib

常用 alex hex imp 分割 isa port 計算機 存在

一、 time模塊

表示時間我們通常用三種形式:

  • 時間戳(timestamp):通常來說,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。我們運行“type(time.time())”,返回的是float類型。
  • 格式化的時間字符串(Format String)
  • 結構化的時間(struct_time):struct_time元組共有9個元素共九個元素:(年,月,日,時,分,秒,一年中第幾周,一年中第幾天,夏令時)
import time
print(time.time()) #時間戳:1498025310.887425
print(time.strftime("%Y-%m-%d %X
")) #格式化的時間字符串:2017-06-21 14:08:30 print(time.localtime()) #本地時區的struct_time print(time.gmtime()) #UTC時區的struct_time 結果: 1498025310.887425 2017-06-21 14:08:30 time.struct_time(tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=14, tm_min=8, tm_sec=30, tm_wday=2, tm_yday=172, tm_isdst=0) time.struct_time(tm_year=2017, tm_mon=6
, tm_mday=21, tm_hour=6, tm_min=8, tm_sec=30, tm_wday=2, tm_yday=172, tm_isdst=0)

三者的轉換關系:

技術分享

計算機認識的時間只能是‘時間戳‘格式,而程序員可處理的或者說人類能看懂的時間有: ‘格式化的時間字符串‘,‘結構化的時間‘。

import time
print(time.time())
print(time.localtime())

#將結構化的時間轉換為格式化的字符串時間
print(time.strftime("%Y-%m-%d %X", time.localtime()))

#將結構化的時間轉換為時間戳
print(time.mktime(time.localtime())) #將時間戳轉換為結構化的時間 print(time.localtime(
1498025310)) #將格式化的字符串時間轉換為結構化的時間 print(time.strptime("2017-06-21 16:55:36", "%Y-%m-%d %X")) 結果: 1498035729.0793116 time.struct_time(tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=17, tm_min=2, tm_sec=9, tm_wday=2, tm_yday=172, tm_isdst=0) 2017-06-21 17:02:09 1498035729.0 time.struct_time(tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=14, tm_min=8, tm_sec=30, tm_wday=2, tm_yday=172, tm_isdst=0) time.struct_time(tm_year=2017, tm_mon=6, tm_mday=21, tm_hour=16, tm_min=55, tm_sec=36, tm_wday=2, tm_yday=172, tm_isdst=-1)

技術分享

#將結構化的時間轉換為字符串時間
print(time.asctime(time.localtime()))
print(time.asctime()) #如果沒有參數,將會將time.localtime()作為參數傳入。
print(我是分割線---------------)
#將時間戳轉換為字符串時間
print(time.ctime(time.time()))
print(time.ctime()) #如果沒有參數,將會將time.time()作為參數傳入。
結果:
Wed Jun 21 22:19:16 2017
Wed Jun 21 22:19:16 2017
我是分割線---------------
Wed Jun 21 22:19:16 2017
Wed Jun 21 22:19:16 2017

二、 random模塊

import random 
print(random.random()) #(0,1)----float 大於0且小於1之間的小數 結果:0.3869734571949781
print(random.randint(1,3)) #[1,3] 大於等於1且小於等於3之間的整數 結果:3
print(random.randrange(1,3)) #[1,3) 大於等於1且小於3之間的整數 結果:1
print(random.choice([1,abc,[a,23,world]])) #1或者‘abc‘或者[‘a‘,23,‘world‘] 結果:[‘a‘, 23, ‘world‘] 
print(random.sample([1,abc,[a,23,world]],2)) #列表元素任意2個組合 結果:[[‘a‘, 23, ‘world‘], ‘abc‘] 
print(random.uniform(1,3)) #大於1小於3的小數 結果:2.164429956472153 

l = [1,2,4,5,9]
random.shuffle(l)
print(l) #打亂l的順序,相當於"洗牌"[5, 2, 9, 4, 1]

生成隨機驗證碼實例:

import random
def verify_code():
    res = ""
    for i in range(5):
        res1 = random.randint(1,9)
        res2 = chr(random.randint(97,122))
        res3 = chr(random.randint(65,90))
        res4 = random.choice([str(res1),res2,res3])
        res +=res4
    return res

print(verify_code())
結果:
IcglH

三 、os模塊

os模塊是與操作系統交互的一個接口

需要掌握的應用:

os.getcwd() 獲取當前工作目錄,即當前python腳本工作的目錄路徑
os.chdir("dirname")  改變當前腳本工作目錄;相當於shell下cd
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.path.abspath(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.join(path1[, path2[, ...]])  將多個路徑組合後返回,第一個絕對路徑之前的參數將被忽略
os.path.getatime(path)  返回path所指向的文件或者目錄的最後存取時間
os.path.getmtime(path)  返回path所指向的文件或者目錄的最後修改時間
os.path.getctime(path) 回path所指向的文件或者目錄的創建時間 os.path.getsize(path) 返回path的大小

選擇性掌握的應用:

os.path.split(path)  將path分割成目錄和文件名二元組返回
os.path.isabs(path)  如果path是絕對路徑,返回True
os.path.isfile(path)  如果path是一個存在的文件,返回True。否則返回False
os.path.isdir(path)  如果path是一個存在的目錄,則返回True。否則返回False

示例:

import os
print(os.getcwd())
os.chdir(rC:\Users\Administrator\PycharmProjects\untitled4)
print(os.getcwd())
print(我是分割線--------)
print(os.listdir(rC:\Users\Administrator\PycharmProjects\untitled4\a))
print(我是分割線--------)
res = os.stat(rC:\Users\Administrator\PycharmProjects\untitled4\a\b\c\d)
print(res)
print(res.st_ctime)
print(我是分割線--------)
dirname,basename=os.path.split(rC:\Users\Administrator\PycharmProjects\untitled4\a\a.txt)
print(dirname)
print(basename)
print(我是分割線--------)
s1=rC:\Users\Administrator\PycharmProjects\untitled4\a\b\c
s2=rc.txt
res=os.path.join(s1,s2)
print(res)
結果:
C:\Users\Administrator\PycharmProjects\untitled
C:\Users\Administrator\PycharmProjects\untitled4
我是分割線--------
[a.txt, b]
我是分割線--------
os.stat_result(st_mode=16895, st_ino=7881299347966345, st_dev=1221946964, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1498052199, st_mtime=1498052199, st_ctime=1498052199)
1498052199.7336605
我是分割線--------
C:\Users\Administrator\PycharmProjects\untitled4\a
a.txt
我是分割線--------
C:\Users\Administrator\PycharmProjects\untitled4\a\b\c\c.txt

四、hashlib模塊

hash:一種算法 ,3.x裏代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
三個特點:
1.內容相同則hash運算結果相同,內容稍微改變則hash值則變
2.不可逆推
3.相同算法:無論校驗多長的數據,得到的哈希值長度固定。

import hashlib
 
m=hashlib.md5()# m=hashlib.sha256()
 
m.update(hello.encode(utf8))
print(m.hexdigest())  #5d41402abc4b2a76b9719d911017c592
 
m.update(alvin.encode(utf8))
 
print(m.hexdigest())  #92a7e713c30abbb0319fa07da2a5c4af
 
m2=hashlib.md5()
m2.update(helloalvin.encode(utf8))
print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af

‘‘‘
註意:把一段很長的數據update多次,與一次update這段長數據,得到的結果一樣
但是update多次為校驗大文件提供了可能。
‘‘‘

以上加密算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密算法中添加自定義key再來做加密。

import hashlib
 
# ######## 256 ########
 
hash = hashlib.sha256(898oaFs09f.encode(utf8))
hash.update(alvin.encode(utf8))
print (hash.hexdigest())#e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7

實例:模擬撞庫破解密碼

import hashlib
passwds=[
    alex3714,
    alex1313,
    alex94139413,
    alex123456,
    123456alex,
    a123lex,
    ]
def make_passwd_dic(passwds):
    dic={}
    for passwd in passwds:
        m=hashlib.md5()
        m.update(passwd.encode(utf-8))
        dic[passwd]=m.hexdigest()
    return dic

def break_code(cryptograph,passwd_dic):
    for k,v in passwd_dic.items():
        if v == cryptograph:
            print(密碼是===>\033[46m%s\033[0m %k)

cryptograph=aee949757a2e698417463d47acac93df
break_code(cryptograph,make_passwd_dic(passwds))

模擬撞庫破解密碼

python 還有一個 hmac 模塊,它內部對我們創建 key 和 內容 進行進一步的處理然後再加密:

1 import hmac
2 h = hmac.new(alvin.encode(utf8))
3 h.update(hello.encode(utf8))
4 print (h.hexdigest())#320df9832eab4c038b6c1d7ed73a5940

Python--模塊之time、random、os、hashlib