项目开发常用复用的工具函数
- 时间相关
获取两个日期之间的所有日期 返回list
1
2
3
4
5
6
7
8
9
10import datetime
def getEveryDay(begin_date,end_date):
date_list = []
begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date,"%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
根据时间差获取日期
1 | import datetime |
- 数据操作相关
对某些列做四舍五入操作
1
2
3
4
5def round_df_col(df, col_list=qty_list):
col_list.extend(['ben_'+str(i) for i in col_list])
for col in list(df):
if col in col_list:
df[col]= df[col].round(0)
python 生成row number()
1 | def row_number(dataset, partionby, orderby, asc): |
python行转列辅助函数
1 | import pandas as pd |
字典操作
1
2
3
4
5
6
7
8
9import json
def dump_json(obj, fn, encoding='utf-8'):
with open(fn, 'w', encoding=encoding) as fout:
json.dump(obj, fout, ensure_ascii=False, indent=4)
def load_json(fn, encoding='utf-8'):
with open(fn, 'r', encoding=encoding) as fin:
return json.load(fin)文件操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import os
import shutil
def make_path(file_path):
if not os.path.exists(file_path):
os.makedirs(file_path)
def file_copy(file_path, target_path):
make_path(target_path)
shutil.copy(file_path, target_path)
def folder_copy(from_folder, to_folder):
pathDir = os.listdir(from_folder)
for filename in pathDir:
from_path = os.path.join(from_folder, filename)
to_path = to_folder
file_copy(from_path, to_path)