python常用的工具方法
2020-05-09 本文已影响0人
LeslieFind
一、json格式输出
response = {'errno': 0, 'errmsg': 'ok', 'data': {'id': 730}, 'expire_day': '1970-01-01 08:00:00'}
json.dumps(response, indent=4, ensure_ascii=False)
image.png
二、生成十位编号
import random,string
num = string.ascii_letters + string.digits
traceId = "".join(random.sample(num,10))
输出:
'traceId': '3RF9z0ExyP'
三、url转码,解码
import urllib.parse
urllib.parse.quote("我是好孩子")
urllib.parse.unquote("title=%E4%B8%8D%E6%84%A7%E6")
四、多符号分隔字符串
import re
line = "as\tqw;yu"
temp_line = re.split(r'[\t;]',line)
五、时间差的计算
5.1
import datetime
starttime = datetime.datetime.now()
'''中间漫长处理'''
endtime = datetime.datetime.now()
#单位:s
print((endtime - starttime).seconds)
#单位:ms
print((endtime - starttime).microseconds)
5.2
# import datetime
# import arrow
def getTime(self, flag,dayhourminute):
'''
获取几小时之前,几分钟前,几天前,几个月前,及几年前的具体时间 flag, 1:天;2:小时;3:分钟;4:月,5:年
:param flag: 1:天;2:小时;3:分钟;4:月,5:年
:param dayhourminute: 整数值
:return: 具体时间 %Y-%m-%d %H:%M:%S
'''
tn = datetime.datetime.now()
t = None
ttime =''
if flag <= 1:
if flag == 1:
t = datetime.timedelta(days=dayhourminute)
elif flag == 2:
t = datetime.timedelta(hours=dayhourminute)
elif flag == 3:
t = datetime.timedelta(minutes=dayhourminute)
strtime = tn - t
ttime = strtime.strftime('%Y-%m-%d %H:%M:%S')
else:
dt = arrow.now()
if flag == 4:
ttime = dt.shift(months=-dayhourminute).format("YYYY-MM-DD HH:MM:SS")
elif flag == 5:
ttime = str(int(datetime.datetime.now().strftime("%Y"))-dayhourminute)+"-"+datetime.datetime.now().strftime("%m-%d")
return ttime
六、对url的解析(urllib)
from urllib.parse import urlparse, parse_qs,urlunparse, urlencode
if __name__ == '__main__':
url = "https://p0.ai.com/t01ddfbd8a91e1efe3a.jpg?size=1777x2462"
# 解析http请求各个部分
parsed_url = urlparse(url)
print(parsed_url)
# path为接口
print(parsed_url.path)
# qs为解析的参数
qs = parse_qs(parsed_url.query)
print(qs)
#输出:
#ParseResult(scheme='https', netloc='p0.ai.com', path='/t01ddfbd8a91e1efe3a.jpg', params='', query='size=1777x2462', fragment='')
#/t01ddfbd8a91e1efe3a.jpg
#{'size': ['1777x2462']}
补充,如果对域名改host也可以用这个库
url="http://www.baidu.com"
r=urlparse(url)
url = url.replace(r.netloc,'123.125.81.117') # 地址是这个ip
七、文件名称拆分
import os
if __name__ == '__main__':
path = '123.TXT'
path_split = os.path.splitext(path)
print(path_split)
print(path_split[0])
print(path_split[1])
print(path_split[1].lower())
#输出:
#('123', '.TXT')
#123
#.TXT
#.txt