Ⅱ handy built-in module

A, shelve module

  1. shelve also provide us with python serialization tool, easier than pickle with some of them,
    shelve only provide us with a open approach is the key to access, use and similar dictionary

    import shelve
    f = shelve.open('shelve_file')
    f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
    f.close()
    
    import shelve
    f1 = shelve.open('shelve_file')
    existing = f1['key']  #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
    f1.close()
    print(existing)
  2. This module has a limit, it does not support multiple applications at the same time to the same DB for writing. So when we know our application if the read-only operation, we can make shelve open by read-only DB

    import shelve
    f = shelve.open('shelve_file', flag='r')
    existing = f['key']
    f.close()
    print(existing)
  3. Due to shelve the record is not going to be any changes to persistent objects by default, so we need to modify the default parameters in shelve.open () when otherwise modify the object will not be saved

    import shelve
    f1 = shelve.open('shelve_file')
    print(f1['key'])
    f1['key']['new_value'] = 'this was not here before'
    f1.close()
    
    f2 = shelve.open('shelve_file', writeback=True)
    print(f2['key'])
    f2['key']['new_value'] = 'this was not here before'
    f2.close()
  4. writeback mode has advantages and disadvantages advantage of reducing the probability of our mistakes, and make persistent object to the user more transparent; but this way not all cases need to, first of all, for future use writeback, shelf in open () time will add additional memory consumption, and at the time when the DB close () will cache of every object written to the DB, which will bring additional latency because there is no way of knowing shelve which objects to modify the cache, which objects have not changed, so all objects will be written.

Two, time module

  1. In python, there are usually three ways to represent time:

    • Timestamp (times tamp): Generally speaking, the timestamp indicates that from January 1970 00:00:00 1st offset press in seconds we run "type (time.time ())",. It returns a float

      import time
      t = time.time()
      print(t)
    • Formatted time string (format time):

      import time
      t1 = time.strftime('%Y-%m-%d %H:%M:%S') # 必须是ascii码支持的
      print(t1)  # 2019-06-28 19:04:00
      ------------------------------------------------
      t2 = time.strftime('%Y{}%m{}%d{} %H:%M:%S')
      t3 = t2.format('年', '月', '日')
      print(t3)  # 2019年06月28日 19:04:00
      %y 两位数的年份表示(00-99)
      %Y 四位数的年份表示(000-9999)
      %m 月份(01-12)
      %d 月内中的一天(0-31)
      %H 24小时制小时数(0-23)
      %I 12小时制小时数(01-12)
      %M 分钟数(00=59)
      %S 秒(00-59)
      %a 本地简化星期名称
      %A 本地完整星期名称
      %b 本地简化的月份名称
      %B 本地完整的月份名称
      %c 本地相应的日期表示和时间表示
      %j 年内的一天(001-366)
      %p 本地A.M.或P.M.的等价符
      %U 一年中的星期数(00-53)星期天为星期的开始
      %w 星期(0-6),星期天为星期的开始
      %W 一年中的星期数(00-53)星期一为星期的开始
      %x 本地相应的日期表示
      %X 本地相应的时间表示
      %Z 当前时区的名称
      %% %号本身
    • Structured time, component (struct time):

      t = time.localtime()
      print(t)
      # time.struct_time(tm_year=2019, tm_mon=6, tm_mday=28, tm_hour=19, tm_min=12, tm_sec=59, tm_wday=4, tm_yday=179, tm_isdst=0)
    • Summary: The computer is able to identify the timestamp of the time; time string format is one can read time; structured tuple is used to time the operation time

  2. Conversion between several formats

    import time
    # 格式化时间--->结构化时间
    ft = time.strftime('%Y-%m-%d %H:%M:%S')
    st = time.strptime(ft, '%Y-%m-%d %H:%M:%S') # 此处格式必须与上方相同
    print(st)
    # 结构化时间--->时间戳
    t = time.mktime(st)
    print(t)
    # 时间戳--->结构化时间
    t = time.time()
    st = time.localtime(t)
    print(st)
    # 结构化时间--->格式化时间
    ft = time.strftime('%Y-%m-%d %H:%M:%S', st)
    print(ft)
    #结构化时间 --> %a %b %d %H:%M:%S %Y串
    #time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串
    >>>time.asctime(time.localtime(1500000000))
    'Fri Jul 14 10:40:00 2017'
    >>>time.asctime()
    'Mon Jul 24 15:18:33 2017'
    
    #时间戳 --> %a %d %d %H:%M:%S %Y串
    #time.ctime(时间戳)  如果不传参数,直接返回当前时间的格式化串
    >>>time.ctime()
    'Mon Jul 24 15:19:07 2017'
    >>>time.ctime(1500000000)
    'Fri Jul 14 10:40:00 2017' 
    
    t = time.time()
    ft = time.ctime(t)
    print(ft)
    
    st = time.localtime()
    ft = time.asctime(st)
    print(ft)
  3. Calculate the time difference

    t1 = '2017-09-11 08:30:00'
    t2 = '2019-05-11 08:50:00'
    st1 = time.strptime(t1, '%Y-%m-%d %H:%M:%S')
    st2 = time.strptime(t2, '%Y-%m-%d %H:%M:%S')
    tt1 = time.mktime(st1)
    tt2 = time.mktime(st2)
    time_dif = tt2 - tt1
    struct_time = time.localtime(time_dif)
    print(struct_time)
    print(f'过去了{struct_time.tm_year-1970}年{struct_time.tm_mon-1}月{struct_time.tm_mday-1}天{struct_time.tm_hour}小时{struct_time.tm_min}分钟{struct_time.tm_sec}秒')

Three, datetime module

import datetime
now_time = datetime.datetime.now()
# 现在的时间2019-06-28 19:47:21.339993
--------------------------------------------------
# 只能调整的字段: week days hours minutes seconds
print(datetime.datetime.now() + datetime.timedelta(weeks=3)) # 三周后
print(datetime.datetime.now() + datetime.timedelta(weeks=-3)) # 三周前
print(datetime.datetime.now() + datetime.timedelta(days=-3)) # 三天前
print(datetime.datetime.now() + datetime.timedelta(days=3)) # 三天后
print(datetime.datetime.now() + datetime.timedelta(hours=5)) # 5小时后
print(datetime.datetime.now() + datetime.timedelta(hours=-5)) # 5小时前
print(datetime.datetime.now() + datetime.timedelta(minutes=-15)) # 15分钟前
print(datetime.datetime.now() + datetime.timedelta(minutes=15)) # 15分钟后
print(datetime.datetime.now() + datetime.timedelta(seconds=-70)) # 70秒前
print(datetime.datetime.now() + datetime.timedelta(seconds=70)) # 70秒后
--------------------------------------------------
# 可直接调整到指定的 年 月 日 时 分 秒 等
now_time = datetime.datetime.now()
print(current_time.replace(year=1977))  # 直接调整到1977年
print(current_time.replace(month=1))  # 直接调整到1月份
print(current_time.replace(year=1989,month=4,day=25))  # 1989-04-25 18:49:05.898601
--------------------------------------------------
# 将时间戳转化成时间
print(datetime.date.fromtimestamp(1232132131))  # 2009-01-17

Four, random module

import random
# 随机小数
random.random()  # 大于0且小于1之间的小数
random.uniform(1, 3) # 大于1小于3的小数
# ----------------------------------------
# 随机整数
random.randint(1, 5) # 大于等于1且小于等于5之间的整数
random.randrange(1, 10, 2) # 大于等于1且小于10之间的奇数
# ----------------------------------------
# 随机选择一个返回
random.choice([1, '23', [4, 5]])  # 1或者23或者[4,5]

# 随机选择多个返回
random.sample([1, '23', [4, 5]], 2) # 列表元素任意2个组合
# ----------------------------------------
# 打乱列表顺序
lst = [1, 2, 3, 4, 5, 6]
random.shuffle(lst)
print(lst) # 随机顺序
# 模拟随机验证码
import random
def v_code():
    code = ''
    for i in range(5):
        num = random.randint(0, 9)
        alf = chr(random.randint(65, 90))  # chr()通过序号查字符
        add = random.choice([num, alf])
        code = "".join([code, str(add)])
    return code

print(v_code())

Guess you like

Origin www.cnblogs.com/zyyhxbs/p/11104569.html