一、Python时间工具类
- 从字符串中提取时间字符串;
例如:从今天 2022年05月01日 明天
中匹配2022年5月15日
- 将时间字符串格式化为自己想要的形式;
例如:将 20220515
转化为 2022年05月01日
import re
import time
def search_time(text):
"""
匹配 2022年5月15日、2022/5/15、20220515
:param text: 例如:今天 2022年05月01日 明天
:type text: str
"""
pattern = re.search('\d{0,4}[\-/年]{0,1}\d{1,2}[\-/月]{0,1}\d{1,2}[日号]{0,1}', text)
timeStr = pattern.group()
print("search_time:" + timeStr)
return timeStr
def format_time(timeStr):
"""
将 20220515 转化为 2022年05月01日
:type timeStr: str
"""
timeStruct = time.strptime(timeStr, "%Y%m%d")
strTime = time.strftime("%Y年%m月%d日", timeStruct)
print("format_time:" + strTime)
return strTime
search_time("今天 2022年5月15日 明天")
search_time("今天 2022/5/15 明天")
search_time("今天 20220515 明天")
search_time("今天 0515 明天")
format_time("20220515")
二、文件工具类
- 根据关键词 查找对应目录下的文件 返回文件名
例如:输入对应路径以及关键词abc
,可获取文件名abcdef.txt
import os
def get_filename_by_key(dir, search_key):
"""根据关键词 查找对应目录下的文件 返回文件名
:param dir: 要查找的目录
:type dir: str
:param search_key: 搜索关键词
:type search_key: str
"""
for fileName in os.listdir(dir):
if search_key in fileName:
return fileName
三、数据处理
- 三个数字之间加一个逗号
例如:将123456789
格式化为123,456,789
- 浮点值不保留小数点
例如:将12.13
格式化为12
- 转化为百分比并保留两个小数点(
不四舍五入
)
例如:将0.33335
格式化为33.33%
import math
def format_comma(num):
"""
三个数字加一个逗号
:param numCount: 例如:123456789
:type numCount: int
"""
return "{:,.{}f}".format(num, 0)
def format_trunc(fcount):
"""
不保留小数点
:param fcount: 例如:12.13
"""
return math.trunc(fcount)
def format_percent(data):
"""
保留两个小数点,加%
:param numCount: 例如:123456789
:type numCount: int
"""
percent_data = data * 100
n = 2
percent = math.floor(percent_data * 10 ** n) / (10 ** n)
print("percent", percent)
return str(percent) + "%"