python 自用函数

下面是一些工作过程中比较常见的工具方法,但不代表最终答案。希望能对你有所帮助,如果您有更好更多的方法工具,欢迎推荐!

1. 获取每日的时间列表

# -*- coding:utf-8 -*-
import datetime
def getBetweenDay():
    date_list = []

    #获取开始与结束时间,范例为获取最近7天时间
    now_time = datetime.datetime.now()
    begin_day = (now_time+datetime.timedelta(days=-7)).strftime("%Y%m%d")
    end_day = (now_time+datetime.timedelta(days=-1)).strftime("%Y%m%d")

    begin_date = datetime.datetime.strptime(begin_day, "%Y%m%d")
    end_date = datetime.datetime.strptime(end_day, "%Y%m%d")

    while begin_date <= end_date:
        date_str = begin_date.strftime("%Y%m%d")
        date_list.append(date_str)
        begin_date += datetime.timedelta(days=1)
    return date_list

2. 计量单位格式化输出

def formatData(value):  
    units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB' ]  
    try:  
        size = float(value)  
    except:  
        return False  
  
    if size < 0:  
        return False  
    _OVER_PB = 1024 * 1024 * 1024 * 1024
    if size >= _OVER_PB:  # 超过PB的限制  
        size_h = '{0:.2f} PB'.format(size / _OVER_PB)  
        return size_h  
  
    for i, unit in enumerate(units):  
        if size >= 1024**(i+2):  # 下一个单位是KB,所以是1024**(i+2)  
            size = float('%.4f' %( size / 1024**(i+1)))  
        else:  
            size_h = '{0:.2f} {1}'.format(size, unit)  
            return size_h  
  
    # 超大数据仅保留到PB级  
    size_h = '{0:.2f} {1}'.format(size, units[-1])  
    return size_h

3. 元组转换为字典

# -*- coding:utf-8 -*-
def tuple_to_dic(results):
    """元组转换为字典,字典key为元组第一个值,字典值为元组第二个值的列表集"""
    tmp_dic = {}
    for i in range(len(results)):
        if tmp_dic.has_key(results[i][0]):
            tmp_dic[results[i][0]].append(results[i][1])
        else:
            tmp_dic[results[i][0]] = []
            tmp_dic[results[i][0]].append(results[i][1])
    return tmp_dic

示例:
代码如下

# -*- coding:utf-8 -*-

results = ((20190713,1),(20190713,2),(20190713,3),(20190714,4))

def tuple_to_dic(results):
    """元组转换为字典,字典key为元组第一个值,字典值为元组第二个值的列表集"""
    tmp_dic = {}
    for i in range(len(results)):
        if tmp_dic.has_key(results[i][0]):
            tmp_dic[results[i][0]].append(results[i][1])
        else:
            tmp_dic[results[i][0]] = []
            tmp_dic[results[i][0]].append(results[i][1])
    return tmp_dic
dic = tuple_to_dic(results)
print dic

输出结果为

{20190713: [1, 2, 3], 20190714: [4]}

4. 文件锁

写此函数的初衷是用作监控,可以更细粒度的判断某一个事件发生后持续多长时间(多少次)来触发告警。

# -*- coding:utf-8 -*-
import os,sys
def sock(task, num, interval=60):
    current_time = int(time.time())
    sock_path = '.alarm'
    sock_file = os.path.join(sock_path, f"{task}.sock")
    if not os.path.exists(sock_path):
        os.mkdir(sock_path)

    if not os.path.isfile(sock_file):
        with open(sock_file, mode='w', encoding='utf-8') as fd:
            create_time = int(time.time())
            fd.write(f"0,{create_time}")

    # current num
    fd = open(sock_file, 'r')
    line = fd.read()
    cn = line.split(',', 1)[0] if line.split(',', 1)[0] else 0
    create_time = line.split(',', 1)[1] if line.split(',', 1)[1] else current_time
    fd.close()
    cn = int(cn) + 1

    # 判断是否在统计周期内,允许5s误差
    if int(current_time) - int(create_time) <= interval + 5:
        if cn >= num:
            with open(sock_file, mode='w', encoding='utf-8') as fd:
                fd.write(f"0,{current_time}")
            return True
        else:
            with open(sock_file, mode='w', encoding='utf-8') as fd:
                fd.write(f"{cn},{current_time}")
            return False
    else:
        with open(sock_file, mode='w', encoding='utf-8') as fd:
            fd.write(f"0,{current_time}")
        return False

持续更新中...

posted @ 2019-07-04 13:47  guoew  阅读(430)  评论(0编辑  收藏  举报