第15天 常用模块

it2024-01-18  71

一、常用模块

什么是时间戳

时间戳就是以秒为单位表示的到格林威治时间1970年1月1日0时0分0秒的时间差

保存时间的时候保存时间戳要比直接保存时间信息更加节约内存 对时间戳进行加密比字符串时间加密要方便

1.time() - 获取当前时间(返回的是当前时间的时间戳) t1 = time.time() print(t1) # 1603093084.514837 ‘2020/10/19 15:46:30’

2.time.localtime() time.localtime() - 获取当前的本地时间,返回struct_time对象 t2 = time.localtime() print(t2)

time.localtime(时间戳) - 获取指定时间戳对应的本地时间,返回struct_time对象 t3 = time.localtime(0) print(t3)

t4 = time.localtime(1603093084.514837) print(t4)

3.time.strftime(时间格式字符串, 结构体时间) - 将结构体转换成指定格式的字符串时间

# '2020/10/19' s1 = time.strftime('%Y/%m/%d', t4) print(s1) # 2020/10/19 # xxxx-xx-xx xx:xx:xx s2 = time.strftime('%Y-%m-%d %H:%M:%S', t4) print(s2) # 2020-10-19 15:38:04 # 星期一 下午3:38 s3 = time.strftime('%A %p%H:%M', t4) print(s3) # Mon PM15:38 def china_time(t_str: str): table = { 'PM': '下午', 'AM': '上午', 'Monday': '星期一', 'Mon': '星期一' } for key in table: t_str = t_str.replace(key, table[key]) return t_str print(china_time(s3)) time.strptime(字符串, 时间格式字符串) - 将字符串时间转换成结构体时间 s2 = ‘2000-10-29’ t5 = time.strptime(s2, ‘%Y-%m-%d’) print(t5)

二、hashib模块

hashlib模块主要提供hash加密相关的算法来对数据进行加密处理

hash加密(hash摘要)的特点: a. 加密结果不可逆(不能通过密文/摘要去获取到原文) b. 同一个数据通过相同的算法加密之后的结果是一样的 c. 不同的数据通过相同的算法加密之后的长度相同

hash摘要的应用场景: a. 密码保存 b. 数据完整性的验证 “”"

1.根据算法创建hash对象(md5和shaXXX) hashlib.算法名() hash = hashlib.md5()

添加需要生成摘要/密文的数据 hash对象.update(数据的二进制) hash.update(‘123456’.encode(encoding=‘utf-8’))

3.生成摘要 dig = hash.hexdigest() print(dig)

最新回复(0)