ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

人生苦短,我学python day15 时间、hash和json

2021-09-08 23:03:05  阅读:199  来源: 互联网

标签:hash python t5 字符串 json time print 苦短


一、时间模块

  • python和时间相关的模块有两个;time、datetime
1.时间戳
  • 指的是当前时间到1970年1月1日0时0秒(指的是格林威治时间)的时间差(单位是秒)
  • 使用时间戳保存时间比使用字符串保存时间所占用的内容要少很多;
  • 通过时间戳对时间进行加密更简单,对时间进行一个数学运算
  • 1608945740.9762201(保存的时候大概需要4个字节) -> 包含了年、月、日、时、分、秒、毫秒
    ‘2020-12-26 9:29:30’(保存的时候至少需要18个字节)
2.time()
  • 获取当前时间,返回的是时间戳

    t1 = time.time()
    print(t1)               # 1608945666.0906377
    print(t1, type(t1))     # 1608945740.9762201 <class 'float'>
    
  • localtime(时间戳) - 将时间戳转换成本地的结构体时间

    t2 = time.localtime(0)
    print(t2)
    
    t4 = time.localtime(1608945666.0906377)
    print(t4)
    print(f'{t4.tm_year}-{t4.tm_mon}-{t4.tm_mday} {t4.tm_hour}:{t4.tm_min}:{t4.tm_sec}')    # 2020-12-26 9:21:6
    
  • 练习:自己封装一个函数,将结构体时间转换为字符串时间,格式是:‘xxx年xxx月xx日 xx:xx:xx’

    def struct_convert(t0: time.struct_time, str1: str):
        return f'{t0.tm_year}{str1}{t0.tm_mon}{str1}{t0.tm_mday} {t0.tm_hour}:{t0.tm_min}:{t0.tm_sec}'
    
  • 练习:自己封装一个函数,将时间戳转换为字符串时间,格式是:‘xxx年xxx月xx日 xx:xx:xx’

    def time_convert(f: float, str1: str):
        t5 = time.localtime(f)
        return f'{t5.tm_year}{str1}{t5.tm_mon}{str1}{t5.tm_mday} {t5.tm_hour}:{t5.tm_min}:{t5.tm_sec}'
    
    print('===============================================')
    print(struct_convert(t2, '-'))             # 2020-12-26 10:3:41
    print(time_convert(1608945666.0906377, '**'))    # 2020-12-26 9:21:6
    
3.将结构体时间转换成字符串时间
  • strftime(时间格式字符串,结构化时间)

  • 时间格式字符串 - 包含时间占位符的字符串
    %Y - 年
    %m - 月
    %d - 日
    %H - 时(24小时制)
    %I - 时(12小时制)
    %M - 分
    %S - 秒
    %a - 星期(英文缩写)
    %A - 星期(英文全拼)
    %w - 星期(用数字表示)
    %b - 月份(英文缩写)
    %B - 月份(英文全拼)
    %p - 上午或者下午(AM/PM)

  • t5 = time.localtime()
    s_t5 = time.strftime('%Y年%m月%d日', t5)
    print(s_t5)         # 2020年12月26日
    
    s_t5 = time.strftime('%Y-%m-%d', t5)
    print(s_t5)         # 2020-12-26
    
    s_t5 = time.strftime('%p', t5)
    print(s_t5)         # 2020-12-26
    
    # 星期几 上午时:分
    t6 = time.strftime('%a %p%H:%M', t5)
    t7 = time.strftime('%A %p%H:%M', t5)
    print(t6)       # Sat AM10:44
    print(t7)       # Saturday AM10:45
    
4.sleep(时间) - 程序暂停指定时间(单位s)
  • time.sleep(2)
    

二、datetime

  • time - 时分秒
    date - 年月日
    datetime - 年月日时分秒

  • print(time())
    t1 = date.today()
    print(t1, t1.year, t1.month, t1.day)       # 2020-12-26 2020 12 26
    
    t2 = datetime.now()
    print(t2)           # 2020-12-26 11:00:30.743720
    
    # 让时间t1加2天
    print(t1 + timedelta(days=2))       # 2020-12-28
    

三、hash摘要

  • hashlib是python自带的一个专门提供hash加密的模块
1.hash加密的特点
  • 同一个数据通过同一个加密算法得到的结果是一样的(加密后的结果叫密文或者摘要)
  • 加密后的结果不可逆
  • 不同大小的数据通过相同的算法生成的摘要的长度是一样的
2.应用场景
  • 创建数据不可逆的密文(加密)
  • 验证数据的完整性和是否被修改
3.怎么生成摘要
  • 根据加密算法创建hash对象

    hash = hashlib.md5()        # 常见hash算法:md5、sha相关
    
    # md5和sha1()的区别
    # md5的内存用的更少,生成的摘要比较短。
    """
    1)相同数据采用相同算法生成的摘要是一样的
    2)不可逆
    3)不同大小的数据通过相同算法产生的摘要的长度是一样的
    """
    
  • 添加加密对象

    # hash对象.update(数据)
    # 数据    -   必须是bytes对象
    hash.update(bytes('123456', encoding='utf-8'))
    
  • 生成摘要(生成密文)

    # hash对象.hexdigest()
    result = hash.hexdigest()       # e10adc3949ba59abbe56e057f20f883e
    print(result)
    result = hash.digest()
    print(result)
    
  • 生成图片摘要

    hash = hashlib.md5()
    with open(r'D:\图片\背景图片\彼岸花\bianhua.jpg', 'rb') as f:
        hash.update(f.read())
        print(hash.hexdigest())     # 9341df07e59467a6830b43f7ea1a38ee
    
  • 生成文本文件的摘要

    hash = hashlib.md5()
    with open('01 时间模块.py', 'rb') as f:
        b3 = f.read()
        hash.update(f.read())
        print(hash.hexdigest())
    
4.补充:字符串和二进制之间的转换
  • 字符串转二进制

    # a.bytes(字符串, encoding='utf-8')
    str1 = 'hello world!'
    b1 = bytes(str1, encoding='utf-8')
    print(type(b1))
    
    # b.字符串.encode()
    b2 = str1.encode()
    print(type(b2))
    
  • 二进制转换为字符串

    # str(二进制, encoding='utf-8')
    s1 = str(b1, encoding='utf-8')
    print(s1, type(s1))
    
    s2 = str(b3, encoding='utf-8')
    print(s2)
    
    hash = hashlib.md5()
    with open(r'D:\文件\其他\人工智能.docx', 'rb') as f:
        b4 = f.read()
        hash.update(f.read())
        print(hash.hexdigest())
    
    # s2 = str(b4, encoding='utf-8')
    # print(s2)
    
    # b.二进制.decode()
    s3 = b1.decode()
    print(s3)
    
四、其他模块
  • math
  • cmath
五、json数据
1.什么是json
  • json是一种数据格式
    json和xml,但是json比xml更轻,更快;xml安全性更高一些(比如说微信)。
  • 格式要求:
    • 有且只有一个数据
    • 这个唯一的数据必须是json支持的数据类型的数据
2.json支持的数据类型
  • 数字类型:包括所有的数字,包含整数、浮点数、正数、负数…,表示的时候直接写,支持科学计数法
  • 字符串:必须是双引号引起来的文本数据,支持转义字符。“abc”,“abc\n123”,"\u4e00abc"
  • 布尔:只有true和false两个值。表示的时候直接写
  • 数组:相当于python的列表,[元素1,元素2,元素3,…]
  • 字典:相当于python的字典,{值1:值1,键1:键2,…},注意:键只能是字符串
  • 空值:null
3.json数据转python
  • 数字 - 整型、浮点型
    字符串 - 字符串
    布尔 - 布尔:小写的首字母变成大写
    数组 - 列表
    字典 - 字典
    null - None

  • json.loads(json数据) - json数据指的是json格式的字符串(字符串去掉引号之后本身就是一个合法的json数据)

    # 'abc' -   不是json格式字符串
    # '"abc"'   -   是json格式字符串
    json.loads('123')
    
    result = json.loads('["hello", 123, false, null]')
    print(result, type(result))     # ['hello', 123, False, None] <class 'list'>
    
  • 练习:获取所有国家的名字和对应的死亡人数,并且按照死亡人数从大到小排序

    with open('data.json', encoding='utf-8') as f:
        result = f.read()
    result = json.loads(result)
    newslist = result['newslist']
    list1 = [(x['provinceName'], x['deadCount']) for x in newslist]
    list1.sort(key=lambda item: item[1], reverse=True)
    print(list1)
    
4.python数据转json
  • int、float -> 数字
    布尔 -> 布尔 ;True,False -> false
    字符串 -> 字符串,引号变成双引号
    列表、元组 -> 数组
    字典 -> 字典
    None -> null

  • # json.dumps(python数据)  ->  将python数据转换成json格式的字符串
    # 120   ->  '120'
    # 'abc' ->  '"abc"'
    result = json.dumps(120)
    print(result, type(result))         # 120 <class 'str'>
    
    result = json.dumps('abc')
    print(result, type(result))         # "abc" <class 'str'>
    
  • # 将数据data写进json文件中
    # 序列化:把对象变成字符串(str)或字节串(bytes)串行化,腌咸菜
    # 如果希望把字典或列表中的数据保存到文件中,可以使用json模块中的dump函数
    with open('data','w') as file:
    	data = json.dump(data,file)
        
    # 从文件data读取数据
    # 反序列化,把字符串或者字节串还原成对象,反串行化,解冻
    with open('data','r') as file:
    	data = json.load(file)
        print(data)
    

标签:hash,python,t5,字符串,json,time,print,苦短
来源: https://blog.csdn.net/weixin_47927271/article/details/120190867

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有