文章目录
- 1. 时间相关操作
- 2. 计算md5值
- 3. 日志类二次封装
1. 时间相关操作
import time
import datetime
def now_datetime(_format="%Y-%m-%d %H:%M:%S") -> str:
"""
获取当前日期时间
:param _format: 日期时间格式,默认:年-月-日 时:分:秒
:return: 当前日期时间
"""
return time.strftime(_format)
def now_timestamp(ms=False) -> int:
"""
获取当前时间戳
:param ms: 是否获取毫秒级时间戳,默认是秒级
:return: 时间戳
"""
timestamp = time.time()
if ms:
return round(timestamp * 1000)
else:
return int(timestamp)
def get_the_datetime(_type: str, n: int, _format="%Y-%m-%d %H:%M:%S"):
"""
获取相对日期时间
:param _type: 类型
:param n: 数值
:param _format: 返回格式
:return: 返回前n天、后n天、前n个小时、后n个小时等
"""
now = datetime.datetime.now()
if _type == "day":
return (now + datetime.timedelta(days=n)).strftime(_format)
elif _type == "hour":
return (now + datetime.timedelta(hours=n)).strftime(_format)
elif _type == "minutes":
return (now + datetime.timedelta(minutes=n)).strftime(_format)
else:
return None
2. 计算md5值
import hashlib
def string_md5(_str) -> str:
"""
计算字符串md5
:param _str: 待计算md5的字符串
:return: md5值
"""
if type(_str) is not bytes:
_str = _str.encode()
my_md5 = hashlib.md5()
my_md5.update(_str)
my_md5_digest = my_md5.hexdigest()
return my_md5_digest
def file_md5(file_path) -> str:
"""
计算文件md5
:param file_path: 待计算md5值的文件
:return: md5值
"""
with open(file_path, 'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
_hash = md5obj.hexdigest()
return _hash
3. 日志类二次封装
import logging
import os
import time
def get_logger():
_logger = logging.getLogger()
_logger.setLevel(logging.NOTSET)
rq = time.strftime('%Y%m%d', time.localtime(time.time()))
log_path = os.path.dirname(__file__) + '/logs/'
if not os.path.exists(log_path):
os.mkdir(log_path)
log_name = log_path + rq + '.log'
fh = logging.FileHandler(log_name, mode='a')
fh.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] [%(filename)s: %(lineno)d]: %(message)s")
fh.setFormatter(formatter)
_logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
ch.setFormatter(formatter)
_logger.addHandler(ch)
return _logger
logger = get_logger()
logger.warning("haha")