...

获取本机 ip 主机名 MAC地址

import socket

def get_local_ip() -> str:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(('1.1.1.1', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

hostname = socket.gethostname()

def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e+2] for e in range(0,11,2)])

时间

时间戳格式化

timeStamp = 1532585103
timetamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timeStamp))
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")

转换为时间戳

a = "2013-10-10 23:40:00"
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
timeStamp = int(time.mktime(timeArray))

日期计算

delta = datetime.timedelta(days=3)
ctime = datetime.datetime.strptime(ctime,'%Y-%m-%d %H:%M:%S')
n_days = ctime + delta
print(n_days.strftime('%Y.%m.%d'))

获取当天日期时间戳

    today = datetime.date.today()
    today_time = int(time.mktime(today.timetuple()))

前 n 天的时间戳

    threeDayAgo = (datetime.datetime.today() - datetime.timedelta(days=3))
    timeStamp = int(time.mktime(threeDayAgo.timetuple()))

判断字符串中文

re.findall('[\u4e00-\u9fa5]{3}', user['name']) # 匹配后三位???

list 的交集 并集 差集

def diff(listA,listB):
    #求交集的两种方式
    retA = [i for i in listA if i in listB]
    retB = list(set(listA).intersection(set(listB)))

    print "retA is: ",retA
    print "retB is: ",retB

    #求并集
    retC = list(set(listA).union(set(listB)))
    print "retC1 is: ",retC

    #求差集,在B中但不在A中
    retD = list(set(listB).difference(set(listA)))
    print "retD is: ",retD

    retE = [i for i in listB if i not in listA]
    print "retE is: ",retE

def main():
    listA = [1,2,3,4,5]
    listB = [3,4,5,6,7]
    diff(listA,listB)

if __name__ == '__main__':
    main()

结果

retA is:  [3, 4, 5]
retB is:  [3, 4, 5]
retC1 is:  [1, 2, 3, 4, 5, 6, 7]
retD is:  [6, 7]
retE is:  [6, 7]

python

PrettyErrors

err 输出美化 [github](