Life is short. I learn python day15 time, hash and json

Posted by walshd on Wed, 08 Sep 2021 23:55:12 +0200

1, Time module

  • There are two time related modules in python; time,datetime
1. Time stamp
  • It refers to the time difference (in seconds) between the current time and 0:00 on January 1, 1970 (Greenwich mean time)
  • Saving time with timestamp takes much less content than saving time with string;
  • It is simpler to encrypt time through time stamp, and carry out a mathematical operation on time
  • 1608945740.9762201 (about 4 bytes are required for saving) - > including year, month, day, hour, minute, second and millisecond
    '2020-12-26 9:29:30' (at least 18 bytes are required when saving)
2.time()
  • Get the current time and return the timestamp

    t1 = time.time()
    print(t1)               # 1608945666.0906377
    print(t1, type(t1))     # 1608945740.9762201 <class 'float'>
    
  • Localtime (timestamp) - converts a timestamp to a local struct time

    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
    
  • Exercise: encapsulate a function to convert the structure time into string time. The format is: 'xx:xx:xx, XXX, xxx'

    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}'
    
  • Exercise: encapsulate a function to convert the time stamp into a string of time. The format is: 'xx:xx:xx, XXX, xxx'

    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. Convert structure time to string time
  • Strftime (time format string, structured time)

  • Time format string - a string containing a time placeholder
    %Y - year
    %m - month
    %d - day
    %H - hour (24-hour system)
    %I - hour (12 hour system)
    %M - min
    %S - seconds
    %a - week (English abbreviation)
    %A - week (English spelling)
    %w - week (in numbers)
    %b - month (English abbreviation)
    %B - month
    %p - morning or afternoon (AM/PM)

  • t5 = time.localtime()
    s_t5 = time.strftime('%Y year%m month%d day', t5)
    print(s_t5)         # December 26, 2020
    
    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
    
    # What day of the week: 1:00 pm
    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 (time) - the specified time of program pause (unit: s)
  • time.sleep(2)
    

2, datetime

  • time - hour, minute and second
    date - mm / DD / yy
    datetime - year month day hour minute second

  • 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
    
    # Let time t1 add 2 days
    print(t1 + timedelta(days=2))       # 2020-12-28
    

3, hash summary

  • hashlib is a module of python that provides hash encryption
1. Features of hash encryption
  • The result of the same data through the same encryption algorithm is the same (the encrypted result is called ciphertext or abstract)
  • The encrypted result is irreversible
  • The length of the summary generated by the same algorithm for data of different sizes is the same
2. Application scenarios
  • Create data irreversible ciphertext (encryption)
  • Verify the integrity of the data and whether it has been modified
3. How to generate a summary
  • Create hash object according to encryption algorithm

    hash = hashlib.md5()        # Common hash algorithms: md5, sha correlation
    
    # Difference between md5 and sha1()
    # md5 uses less memory and generates shorter summaries.
    """
    1)The summary generated by the same algorithm for the same data is the same
    2)Irreversible
    3)The length of summaries generated by the same algorithm for data of different sizes is the same
    """
    
  • Add encrypted object

    # hash object. Update (data)
    # Data - must be a bytes object
    hash.update(bytes('123456', encoding='utf-8'))
    
  • Generate summary (generate ciphertext)

    # hash object. hexdigest()
    result = hash.hexdigest()       # e10adc3949ba59abbe56e057f20f883e
    print(result)
    result = hash.digest()
    print(result)
    
  • Generate picture summary

    hash = hashlib.md5()
    with open(r'D:\picture\Background picture\Higanbana\bianhua.jpg', 'rb') as f:
        hash.update(f.read())
        print(hash.hexdigest())     # 9341df07e59467a6830b43f7ea1a38ee
    
  • Generate a summary of the text file

    hash = hashlib.md5()
    with open('01 Time module.py', 'rb') as f:
        b3 = f.read()
        hash.update(f.read())
        print(hash.hexdigest())
    
4. Supplement: conversion between string and binary
  • String to binary

    # a. Bytes (string, encoding='utf-8 ')
    str1 = 'hello world!'
    b1 = bytes(str1, encoding='utf-8')
    print(type(b1))
    
    # b. String. encode()
    b2 = str1.encode()
    print(type(b2))
    
  • Binary to string

    # Str (binary, 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:\file\other\artificial intelligence.docx', 'rb') as f:
        b4 = f.read()
        hash.update(f.read())
        print(hash.hexdigest())
    
    # s2 = str(b4, encoding='utf-8')
    # print(s2)
    
    # b. Binary. decode()
    s3 = b1.decode()
    print(s3)
    
4, Other modules
  • math
  • cmath
5, json data
1. What is json
  • json is a data format
    json and xml, but json is lighter and faster than xml; xml is more secure (for example, wechat).
  • Format requirements:
    • There is only one data
    • This unique data must be the data type supported by json
2. Data types supported by JSON
  • Number type: includes all numbers, including integers, floating point numbers, positive numbers, negative numbers, etc. it is written directly when it is expressed, and supports scientific counting
  • String: it must be text data enclosed in double quotation marks. Escape characters are supported. “abc”,“abc\n123”,"\u4e00abc"
  • Boolean: there are only two values: true and false. Write directly when expressing
  • Array: the list equivalent to python, [element 1, element 2, element 3,...]
  • Dictionary: equivalent to python dictionary, {value 1: value 1, key 1: Key 2,...}. Note: keys can only be strings
  • Null value: null
3. Transfer JSON data to python
  • Number - integer, floating point
    String - string
    Boolean - Boolean: lowercase initials become uppercase
    Array - List
    Dictionary - Dictionary
    null - None

  • json.loads(json data) - json data refers to a string in json format (the string itself is a legal json data after removing quotation marks)

    # 'abc' - not json format string
    # 'abc' - is a json format string
    json.loads('123')
    
    result = json.loads('["hello", 123, false, null]')
    print(result, type(result))     # ['hello', 123, False, None] <class 'list'>
    
  • Exercise: get the names of all countries and the corresponding number of deaths, and sort them according to the number of deaths from large to small

    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. Convert Python data to json
  • int, float - > number
    Boolean - > Boolean; True,False -> false
    String - > string, quotes become double quotes
    List, tuple - > array
    Dictionary - > dictionary
    None -> null

  • # json.dumps(python data) - > Convert python data into json format string
    # 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'>
    
  • # Write data into json file
    # Serialization: turn objects into strings (str) or byte strings (bytes) for serialization and pickle
    # If you want to save the data in the dictionary or list to a file, you can use the dump function in the json module
    with open('data','w') as file:
    	data = json.dump(data,file)
        
    # Read data from file data
    # Deserialization: restore a string or byte string to an object, deserialize it, and unfreeze it
    with open('data','r') as file:
    	data = json.load(file)
        print(data)
    

Topics: Python JSON Pycharm