Curs 7
Curs 7
Course 7
TIME MODULE
Implements function that allows one to work with time:
o Get current time
o Format time
o Sleep
o Time zone information
t = time.time()
tobj = time.localtime()
tm = time.mktime(tobj)
print (tm)
print (t)
print (time.asctime(tobj)) Output
1604739710.0
1604739710.098777
Sat Nov 7 11:01:50 2020
TIME MODULE
Use strftime to time object to a specified string representation:
Abbreviation Description Abbreviation Description
%H Hour in 24 hour format %M Minute
%I Hour in 12 hour format %S Seconds
%Y Year (4 digits) %A Day of week (name)
%m Month (decimal) %d Day of month (decimal)
%B Month (name) %p AM or PM
Python 3.x
import time
tobj = time.localtime() Output
print (time.strftime("%H:%M:%S - %Y-%m-%d",tobj)) 14:17:25 - 2019-11-10
print (time.strftime("%I%p:%M:%S - %B",tobj)) 02PM:17:25 - November
November,Sunday 10 2019
print (time.strftime("%B,%A %d %Y",tobj))
TIME MODULE
strftime if used without a time object applies the string format to the current time.
Time module also has a function sleep that receives one parameter (the number of
seconds the current script has to wait until it continues its execution).
Python 3.x
import time
for i in range(0,8):
print (time.strftime("%H:%M:%S")) Output
time.sleep(2)#sleep 2 seconds 11:46:15
11:46:17
11:46:19
If no time object structure is provided, 11:46:21
strftime function will use current time to 11:46:23
11:46:25
apply the specified format.
11:46:27
11:46:29
HASHLIB MODULE
Implements function that allows one to compute different cryptographic functions:
o MD5
o SHA-1
o SHA-224
o SHA-384
o SHA-512
o Shake-128
o Shake-256
m = hashlib.md5()
m.update(b"Today")
m.update(b" I'm having")
m.update(b" a Python ") Output
m.update(b"course") 9dea650a4eab481ec0f4b5ba28e3e0b8
print (m.hexdigest())
import hashlib
def GetFileSHA1(filePath):
m = hashlib.sha1()
m.update(open(filePath,"rb").read())
return m.hexdigest() Output
cad7a796be26149218a76661d316685d7de2d56d
While this example is ok, keep in mind that it loads the entire file content in memory !!!
HASHLIB MODULE
The correct way to do this (having a support for large files is as follows):
Python 3.x
import hashlib
def GetFileSHA1(filePath):
try:
m = hashlib.sha1()
f = open(filePath,"rb")
while True:
data = f.read(4096)
if len(data)==0: break
m.update(data)
f.close()
return m.hexdigest()
except:
return ""
DATA SERIALIZATION
Python has several implementations for data serialization.
o JSON
o Pickle
o Marshal
d = { "a":[1,2,3], 000000000 123 034 099 034│058 032 116 114 {"c": tr
000000008 117 101 044 032│034 097 034 058 ue, "a":
"b":100, 000000016 032 091 049 044│032 050 044 032 [1, 2,
"c":True 000000024 051 093 044 032│034 098 034 058 3], "b":
} 000000032 032 049 048 048│125 100}
s = json.dumps(d)
open("serialization.json","wt").write(s)
print (s) Output
{"a": [1, 2, 3], "b": 100, "c": true}
JSON MODULE
Usage (de-serialization):
Python 3.x
import json
data = open("serialization.json","rt").read()
d = json.loads(data)
print (d)
import json
d = json.load(open("serialization.json","rt"))
print (d)
Output
{"a": [1, 2, 3], "b": 100, "c": true}
PICKLE MODULE
Pickle is another way to serialize objects in Python. The serialization is done in a
binary mode.
Pickle can also serialize:
o Functions (defined using def and not lambda)
o Classes
o Functions from modules
PICKLE support multiple version. Be careful when you serialize with Python 2 and try to
de-serialize with Python 3 (not all version supported by Python 3 are also supported by
Python 2).
If you are planning to switch between versions, either check pickle.HIGHEST_PROTOCOL
to see if the highest protocol is compatible or use 0 as the protocol value.
PICKLE MODULE
Python 3.x
Usage (serialization):
import pickle serialization.pickle
FileAddr 000 001 002 003 004 005 006 007 Text
d = {
"a":[1,2,3], 000000000 128 003 125 113│000 040 088 001 Ç♥}q (X☺
000000008 000 000 000 099│113 001 136 088 cq☺êX
"b":100, 000000016 001 000 000 000│097 113 002 093 ☺ aq☻]
"c":True 000000024 113 003 040 075│001 075 002 075 q♥(K☺K☻K
} 000000032 003 101 088 001│000 000 000 098 ♥eX☺ b
000000040 113 004 075 100│117 046 q♦Kdu.
data = open("serialization.pickle","rb").read()
d = pickle.loads(data)
print (d)
import pickle
d = pickle.load(open("serialization.pickle","rb"))
print (d) Output
{"a": [1, 2, 3], "b": 100, "c": true}
MARSHAL MODULE
Marshal is another way to serialize objects in Python. The serialization is done in a
binary mode. Designed for python compiled code (pyc). The binary result is platform-
dependent !!!
Marshal functions:
o marshal.dump (value, file, [version]) marshal
o marshal.dumps(value, [version]) ➔ to obtain the binary representation of the obj in marshal format
o marshal.load(file)
o marshal.loads(string/buffer)
"a":[1,2,3], 000000000 251 218 001 099│084 218 001 097 √┌☺cT┌☺a
"b":100, 000000008 091 003 000 000│000 233 001 000 [♥ Θ☺
000000016 000 000 233 002│000 000 000 233 Θ☻ Θ
"c":True 000000024 003 000 000 000│218 001 098 233 ♥ ┌☺bΘ
} 000000032 100 000 000 000│048 d 0
buffer = marshal.dumps(d)
open("serialization.marshal","wb").write(buffer)
MARSHAL MODULE
Usage (de-serialization):
Python 3.x
import marshal
data = open("serialization.marshal","rb").read()
d = marshal.loads(data)
print (d)
import marshal
d = marshal.load(open("serialization.marshal","rb"))
print (d)
Marshal serialization has a different format in
Python 2 and Python 3 (these two are not Output
compatible). {"a": [1, 2, 3], "b": 100, "c": true}
RANDOM MODULE
Implements different random base functions:
o random.random() ➔ a random float number between 0 and 1
o random.randint(min,max) ➔ a random integer number between [min … max]
o random.choice(list) ➔ selects a random element from a list
o random.shuffle(list) ➔ shuffles the list
o random.sample(list,count) ➔ creates another list from the current one containing count elements
print (random.random())
print (random.randint(5,10)) Output
0.9410874890940395
l = [2,3,5,7,11,13,17,19] 9
print (random.choice(l)) 5
print (random.sample(l,3)) [19, 17, 11]
[13, 17, 11, 5, 2, 19, 7, 3]
random.shuffle(l)
print (l)
ZIPFILE MODULE
Implements different functions to work with a zip archive:
o List all elements from a zip archive
o Extract files
o Add files to archive
o Get file information
o etc
z = zipfile.ZipFile("archive.zip")
f = z.open("MathOps/Simple/Arithmetic.py")
data = f.read()
f.close()
open("my_ar.py","wb").write(data)
z.close()
Method open from zipfile returns a file-like object. You can also specify a password:
Format: ZipFile.open(name, mode='r', pwd=None)
ZIPFILE MODULE
The following script creates a zip archive and add files to it:
Python 3.x
import zipfile
z = zipfile.ZipFile("new_archive.zip","w",zipfile.ZIP_DEFLATED)
z.writestr("test.txt","some texts ...")
z.write("serialization.json")
z.write("serialization.json", "/dir/a.json")
z.writestr("/dir/a.txt","another text ...")
z.close()
writestr method writes the content of a string into a zip file.
write methods add a file to the archive.
When creating an archive one can specify a desire compression: ZIP_DEFLATED,
ZIP_STORED, ZIP_BZIP2 or ZIP_LZMA.