DataComputer.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. import datetime
  2. import math
  3. import traceback
  4. import psycopg2
  5. from unitls.settings import DBServer, flightDB4, databasefileDB, FilePath
  6. dataListLabel = ['序号', '类型', '时间', '数据1', '数据2', '唯一序列', '备1', '备2', '备3', '备4', '备5', '备6']
  7. dbhost, dbport, dbuser, dbpassword,online_host, online_port, online_user, online_password = DBServer()
  8. host=dbhost
  9. port=dbport
  10. user1=dbuser
  11. password=dbpassword
  12. flightDatedb = flightDB4()
  13. databasefileDB = databasefileDB()
  14. class flightDB():
  15. def __init__(self, host, port, user, password, database):
  16. self.conn = psycopg2.connect(
  17. host=host,
  18. port=port,
  19. user=user,
  20. password=password,
  21. database=database
  22. )
  23. self.c = self.conn.cursor()
  24. def initTable(self, tableName: str, primarykey: str, primarykeyStr: str, keyDict: dict):
  25. try:
  26. keyStr = ''
  27. num = 1
  28. for key in keyDict:
  29. if num != len(keyDict):
  30. keyStr += '{} {},\n'.format(key, keyDict[key])
  31. else:
  32. keyStr += '{} {}'.format(key, keyDict[key])
  33. num += 1
  34. curStr = """
  35. create table if not exists {} (
  36. {} {} ,
  37. {}
  38. )
  39. """.format(tableName, primarykey, primarykeyStr, keyStr)
  40. # print(curStr)
  41. self.c.execute(curStr)
  42. self.conn.commit()
  43. except Exception:
  44. print(traceback.format_exc())
  45. #print(curStr)
  46. def insertData(self, tableName: str, data: dict, *args):
  47. try:
  48. # curStr1 = 'insert into {} '.format(tableName)
  49. num = 1
  50. curStr2 = ''
  51. for key in data:
  52. if num != len(data):
  53. curStr2 += '{},'.format(key)
  54. else:
  55. curStr2 += '{}'.format(key)
  56. num += 1
  57. curStr3 = ''
  58. num = 1
  59. for key in data:
  60. if num != len(data):
  61. curStr3 += "'{}',".format(data[key])
  62. else:
  63. curStr3 += "'{}'".format(data[key])
  64. num += 1
  65. curStr = """
  66. insert into {} ({})
  67. values ({})
  68. """.format(tableName, curStr2, curStr3)
  69. #print(curStr)
  70. self.c.execute(curStr)
  71. if args == ():
  72. self.conn.commit()
  73. except Exception:
  74. print(traceback.format_exc())
  75. def lazyInsertData(self, tableName: str, data: dict):
  76. self.insertData(tableName, data, 'lazy')
  77. def FunctionCommit(self):
  78. try:
  79. self.conn.commit()
  80. except Exception:
  81. print(traceback.format_exc())
  82. def FunctionRollback(self):
  83. self.conn.rollback()
  84. def deleteTable(self, tablename: str, *condition: str):
  85. try:
  86. # print(condition)
  87. if condition != ():
  88. curStr = """
  89. delete from {} where {}
  90. """.format(tablename, condition[0])
  91. else:
  92. curStr = """
  93. delete from {}
  94. """.format(tablename)
  95. # print(curStr)
  96. self.c.execute(curStr)
  97. self.conn.commit()
  98. except Exception:
  99. print(traceback.format_exc())
  100. def lazydeleteTable(self, tablename: str, *condition: str):
  101. try:
  102. # print(condition)
  103. if condition != ():
  104. curStr = """
  105. delete from {} where {}
  106. """.format(tablename, condition[0])
  107. else:
  108. curStr = """
  109. delete from {}
  110. """.format(tablename)
  111. # print(curStr)
  112. self.c.execute(curStr)
  113. except Exception:
  114. print(traceback.format_exc())
  115. def deleteTable2(self, tablename: str):
  116. try:
  117. # print(condition)
  118. curStr = """
  119. DROP TABLE IF EXISTS {};
  120. """.format(tablename)
  121. # print(curStr)
  122. self.c.execute(curStr)
  123. self.conn.commit()
  124. except Exception:
  125. print(traceback.format_exc())
  126. def sort_queryTable(self, findkey: str, tablename: str, condition: str, tableKey: str, fn):
  127. try:
  128. curStr = """
  129. select {} from {} where {} order by {} {}
  130. """.format(findkey, tablename, condition, tableKey, fn)
  131. # print(curStr)
  132. self.c.execute(curStr)
  133. return self.c.fetchall()
  134. except Exception:
  135. print(traceback.format_exc())
  136. def sortTable(self, tablename: str, tableKey: str, fn):
  137. try:
  138. curStr = """
  139. select * from {} order by {} {}
  140. """.format(tablename, tableKey, fn)
  141. # print(curStr)
  142. self.c.execute(curStr)
  143. return self.c.fetchall()
  144. except Exception:
  145. print(traceback.format_exc())
  146. def sort_queryTable2(self, findkey: str, tablename: str, condition: str, tableKey: str, fn, tableKey1: str, fn1):
  147. try:
  148. curStr = """
  149. select {} from {} where {} order by {} {},{} {}
  150. """.format(findkey, tablename, condition, tableKey, fn, tableKey1, fn1)
  151. # print(curStr)
  152. self.c.execute(curStr)
  153. return self.c.fetchall()
  154. except Exception:
  155. print(traceback.format_exc())
  156. def getAlldata(self, tablename: str):
  157. try:
  158. curStr = """select * from {}""".format(tablename)
  159. self.c.execute(curStr)
  160. return self.c.fetchall()
  161. except Exception:
  162. print(traceback.format_exc())
  163. def queryTabel(self, tablename: str, key: str, condition: str):
  164. # print(tablename,key,condition)
  165. try:
  166. curStr1 = """
  167. SELECT EXISTS (
  168. SELECT * FROM pg_catalog.pg_tables
  169. WHERE tablename = '{}' AND schemaname = 'public'
  170. );
  171. """.format(tablename.lower())
  172. self.c.execute(curStr1)
  173. result = self.c.fetchall()[0][0]
  174. if result:
  175. curStr = """
  176. select {} from {} where {}
  177. """.format(key, 'public.' + tablename, condition)
  178. # print(key,tablename,condition)
  179. # print(curStr)
  180. self.c.execute(curStr)
  181. return self.c.fetchall()
  182. else:
  183. # print('{} 不存在'.format(tablename))
  184. return None
  185. except Exception:
  186. # print(curStr)
  187. print(traceback.format_exc())
  188. def upDateItem(self, tablename: str, dateDic: dict, condition: str, *args):
  189. try:
  190. setStr = ''
  191. for key in dateDic:
  192. setStr += "{}={},".format(key, dateDic[key])
  193. setStr = setStr[:-1]
  194. curStr = """
  195. update {} set {} where {}
  196. """.format(tablename, setStr, condition)
  197. print(curStr)
  198. if setStr != "":
  199. self.c.execute(curStr)
  200. if args == ():
  201. self.conn.commit()
  202. except Exception:
  203. print(traceback.format_exc())
  204. def lazyUpdateItem(self, tablename: str, dateDic: dict, condition: str):
  205. try:
  206. self.upDateItem(tablename, dateDic, condition, 'lazy')
  207. except Exception:
  208. print(traceback.format_exc())
  209. pass
  210. def getSingledata(self, findkey: str, tablename: str):
  211. try:
  212. curStr = """
  213. select {} from {}
  214. """.format(findkey, tablename)
  215. # print(curStr)
  216. result = self.c.execute(curStr)
  217. return result.fetchall()
  218. except Exception:
  219. print(traceback.format_exc())
  220. def deleteSingledata(self, tablename: str, findkey: str):
  221. try:
  222. curStr = """
  223. delete from {} where {}
  224. """.format(tablename, findkey)
  225. self.c.execute(curStr)
  226. # print(curStr)
  227. self.conn.commit()
  228. except Exception:
  229. print(traceback.format_exc())
  230. def funcExecute(self, string):
  231. self.c.execute(string)
  232. return self.c.fetchall()
  233. def close(self):
  234. try:
  235. self.conn.close()
  236. except Exception:
  237. print(traceback.format_exc())
  238. def TuplefindInDataList(lists: list, type,data, numb): # 返回列表
  239. res_list = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  240. res_list.append(data)
  241. res = ','.join(str(x) for x in res_list)
  242. if lists and len(lists) !=0:
  243. try:
  244. for l in lists:
  245. if type == l[numb]:
  246. lst = [int(x) for x in l[3].split(',')][1:]
  247. lst.append(data)
  248. res= ','.join(str(x) for x in lst)
  249. break
  250. return res
  251. except:
  252. return res
  253. else:
  254. return res
  255. def TuplefindInDataList2(lists: list, type,data, numb, type2, numb2): # 返回列表
  256. res_list = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  257. res_list.append(data)
  258. res = ','.join(str(x) for x in res_list)
  259. if len(lists) !=0:
  260. try:
  261. for l in lists:
  262. if type == l[numb] and type2 == l[numb2]:
  263. lst = [int(x) for x in l[3].split(',')][1:]
  264. lst.append(data)
  265. res= ','.join(str(x) for x in lst)
  266. break
  267. return res
  268. except:
  269. return res
  270. else:
  271. return res
  272. def mytask():
  273. finishdeTask=""
  274. nowDay = datetime.datetime.now().strftime("%Y%m%d").replace("-","")
  275. nowDay_1 = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d").replace("-","")
  276. nowDay_2 = (datetime.date.today() - datetime.timedelta(days=2)).strftime("%Y%m%d").replace("-", "")
  277. initFlightDatabase1(nowDay)
  278. initFlightDatabase1(nowDay_1)
  279. initFlightDatabase1(nowDay_2)
  280. alldata=DataDBUtilsgetData("sortFlight%s" % nowDay, "*", "编号 != ''")
  281. Yalldata=DataDBUtilsgetData("sortFlight%s" % nowDay_1, "*", "编号 != ''")
  282. try:
  283. mytask1 = function1(alldata,Yalldata)
  284. finishdeTask=finishdeTask+"task1/"
  285. except:
  286. mytask1=[]
  287. pass
  288. try:
  289. mytask2 = function2(alldata,Yalldata)
  290. finishdeTask=finishdeTask+"task2/"
  291. except:
  292. mytask2 = []
  293. pass
  294. now = datetime.datetime.now()
  295. startTime = now.replace(hour=0, minute=0, second=0, microsecond=0)
  296. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  297. tstartTime = (now + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  298. taskMainData=getData("taskMain", "*", "'%s' < 任务开始时间 and 任务开始时间 <'%s'"%(startTime,tstartTime))
  299. YtaskMainData = getData("taskMain", "*", "'%s' < 任务开始时间 and 任务开始时间 <'%s'" % (ystartTime, startTime))
  300. try:
  301. mytask3 = function4(taskMainData,YtaskMainData)
  302. finishdeTask=finishdeTask+"task3/"
  303. except:
  304. mytask3=[]
  305. pass
  306. try:
  307. mytask4 = function5()
  308. finishdeTask=finishdeTask+"task4/"
  309. except:
  310. pass
  311. try:
  312. mytask5 = function7()
  313. finishdeTask=finishdeTask+"task5/"
  314. except:
  315. pass
  316. try:
  317. mytask6 = function9()
  318. finishdeTask=finishdeTask+"task6/"
  319. except:
  320. pass
  321. nowday=datetime.date.today()
  322. nowday_1 = datetime.date.today() - datetime.timedelta(days=1)
  323. dy={0:"每日短停",1:"每日航前",2:"每日航后",3:"每日特后前",4:"每日停场",5:"每日短停",6:"每日航前",7:"每日航后",8:"每日特后前",9:"每日停场",10:"每日外委",11:"每日外委",12:"每日总数",13:"每日总数",14:"每日川航",15:"每日川航",16:"已执行",17:"已执行"}
  324. fdb = flightDB(host=online_host,
  325. port=online_port,
  326. user=online_user,
  327. password=online_password,
  328. database=databasefileDB
  329. )
  330. try:
  331. olddata_1=fdb.getAlldata("dataList{}".format(nowDay_1))
  332. except:
  333. olddata_1=[]
  334. try:
  335. olddata_2=fdb.getAlldata("dataList{}".format(nowDay_2))
  336. except:
  337. olddata_2=[]
  338. fdb.lazydeleteTable("dataList{}".format(nowDay_1),"1=1")
  339. fdb.lazydeleteTable("dataList{}".format(nowDay), "1=1")
  340. try:
  341. for ii in range(0,len(mytask1)): ##每日航班分布
  342. if ii in [5,6,7,8,9,11,13,15,17]:
  343. res_data_1=TuplefindInDataList(olddata_2,dy[ii],mytask1[ii],1)
  344. newdic={"类型":dy[ii],"时间":nowday_1,"数据1":res_data_1,"数据2":"",'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  345. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  346. else:
  347. res_data=TuplefindInDataList(olddata_1,dy[ii],mytask1[ii],1)
  348. newdic = {"类型": dy[ii], "时间": nowday, "数据1": res_data, "数据2": "", '唯一序列': "", '备1': "", '备2': "",'备3': "", '备4': "", '备5': "", '备6': ""}
  349. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  350. for ii in mytask2[0].keys():##每刻航班分布
  351. for iii in mytask2[0][ii].keys():
  352. res_data = TuplefindInDataList2(olddata_1, '每刻%s'%iii,mytask2[0][ii][iii],1, ii,2)
  353. newdic={"类型":'每刻%s'%iii,"时间":ii,"数据1":res_data,"数据2":"",'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  354. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  355. for iiii in mytask2[1].keys():
  356. for iiiii in mytask2[1][iiii].keys():
  357. res_data = TuplefindInDataList2(olddata_2, '每刻%s'%iiiii, mytask2[1][iiii][iiiii],1, iiii,2)
  358. newdic={"类型":'每刻%s'%iiiii,"时间":iiii,"数据1":res_data,"数据2":"",'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  359. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  360. #每日任务分布
  361. res_data_1 = TuplefindInDataList(olddata_1, '任务分布', mytask3[1], 1)
  362. res_data_2 = TuplefindInDataList(olddata_1, '任务分布', mytask3[0], 1)
  363. newdic={"类型":'任务分布',"时间":nowday,"数据1":res_data_1,"数据2":res_data_2,'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  364. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  365. res_data_1 = TuplefindInDataList(olddata_2, '任务分布', mytask3[3], 1)
  366. res_data_2 = TuplefindInDataList(olddata_2, '任务分布', mytask3[2], 1)
  367. newdic = {"类型": '任务分布', "时间": nowday_1, "数据1": res_data_1, "数据2": res_data_2, '唯一序列': "", '备1': "", '备2': "",'备3': "", '备4': "", '备5': "", '备6': ""}
  368. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  369. #随机任务
  370. res_data_1 = TuplefindInDataList(olddata_1, '随机任务', mytask4[0], 1)
  371. res_data_2 = TuplefindInDataList(olddata_1, '随机任务', mytask4[1], 1)
  372. newdic={"类型":'随机任务',"时间":nowday,"数据1":res_data_1,"数据2":res_data_2,'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  373. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  374. res_data_1 = TuplefindInDataList(olddata_2, '随机任务', mytask4[2], 1)
  375. res_data_2 = TuplefindInDataList(olddata_2, '随机任务', mytask4[3], 1)
  376. newdic = {"类型": '随机任务', "时间": nowday_1, "数据1":res_data_1,"数据2":res_data_2, '唯一序列': "", '备1': "", '备2': "",'备3': "", '备4': "", '备5': "", '备6': ""}
  377. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  378. #航材工具配送
  379. for i in mytask5[0].keys():
  380. newdic={"类型":'%s配送'%mytask5[0][i]["类型"],"时间":mytask5[0][i]['配送发起时间'],"数据1":mytask5[0][i]['机位'],"数据2":mytask5[0][i]['耗时'],'唯一序列':mytask5[0][i]['任务号'],'备1':mytask5[0][i]['任务级别'],'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  381. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  382. for i in mytask5[1].keys():
  383. newdic={"类型":'%s配送'%mytask5[1][i]["类型"],"时间":mytask5[1][i]['配送发起时间'],"数据1":mytask5[1][i]['机位'],"数据2":mytask5[1][i]['耗时'],'唯一序列':mytask5[1][i]['任务号'],'备1':mytask5[1][i]['任务级别'],'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  384. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  385. #二拖
  386. for i in mytask6[0].keys():
  387. newdic={"类型":'二拖任务',"时间":mytask6[0][i]['创建时间'],"数据1":"","数据2":mytask6[0][i]['耗时'],'唯一序列':mytask6[0][i]['任务号'],'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  388. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  389. for i in mytask6[1].keys():
  390. newdic={"类型":'二拖任务',"时间":mytask6[1][i]['创建时间'],"数据1":"","数据2":mytask6[1][i]['耗时'],'唯一序列':mytask6[1][i]['任务号'],'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  391. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  392. fdb.FunctionCommit()
  393. fdb.close()
  394. #t3 = datetime.datetime.now()
  395. #print(t3 - t2)
  396. print(datetime.datetime.now(), "[计算中心]统计分析写入完毕(%s)"%finishdeTask)
  397. return "ok"
  398. except Exception as e:
  399. print(traceback.format_exc())
  400. fdb.close()
  401. return "fail"
  402. def TuplefindInList(lists: list, args, numb): # 返回列表
  403. res = []
  404. try:
  405. for l in lists:
  406. if args == l[numb]:
  407. res.append(l)
  408. return res
  409. except:
  410. return res
  411. def CountAllList(lists: list): # 返回列表
  412. res = 0
  413. try:
  414. for l in lists:
  415. res+=1
  416. return res
  417. except:
  418. return res
  419. def CountInList(lists: list, args, numb): # 返回列表
  420. res = 0
  421. try:
  422. for l in lists:
  423. if args in l[numb]:
  424. res+=1
  425. return res
  426. except:
  427. return res
  428. def CountInListNot(lists: list, args, numb): # 返回列表
  429. res = 0
  430. try:
  431. for l in lists:
  432. if l[numb] != args:
  433. res+=1
  434. return res
  435. except:
  436. return res
  437. def CountFinshed(lists: list): # 返回列表
  438. res = 0
  439. try:
  440. for l in lists:
  441. if l[3] != "停场" and (l[5] == "3" or l[5] == "4"):
  442. res+=1
  443. return res
  444. except:
  445. return res
  446. def function1(alldata,Yalldata): #查询每日航班的分布
  447. resTR=CountInList(alldata, "短停", 3)
  448. resPEF=CountInList(alldata, "航前", 3)
  449. resPOF=CountInList(alldata, "航后", 3)
  450. resTAF=CountInList(alldata, "特后前", 3)
  451. resST=CountInList(alldata, "停场", 3)
  452. resAll=resTR+resPEF+resPOF+resTAF
  453. resfinsh=CountFinshed(alldata)
  454. YresTR=CountInList(Yalldata, "短停", 3)
  455. YresPEF=CountInList(Yalldata, "航前", 3)
  456. YresPOF=CountInList(Yalldata, "航后", 3)
  457. YresTAF=CountInList(Yalldata, "特后前", 3)
  458. YresST=CountInList(Yalldata, "停场", 3)
  459. YreAll=YresTR+YresPEF+YresPOF+YresTAF
  460. ww=CountInList(alldata, "PB", 0)
  461. yww=CountInList(Yalldata, "PB", 0)
  462. ch=resAll-ww
  463. Ych=YreAll-yww
  464. Yresfinsh=CountFinshed(Yalldata)
  465. return (resTR,resPEF,resPOF,resTAF,resST,YresTR,YresPEF,YresPOF,YresTAF,YresST,ww,yww,resAll,YreAll,ch,Ych,resfinsh,Yresfinsh)
  466. def function2(alldata,Yalldata): #实时任务分布
  467. now=datetime.datetime.now()
  468. startTime = now.replace(hour=0,minute=0, second=0, microsecond=0)
  469. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  470. res=function3(startTime,alldata)
  471. yres = function3(ystartTime, Yalldata)
  472. return(res,yres)
  473. def function4(taskMainData,YtaskMainData):#任务分布
  474. resALL=len(taskMainData) if taskMainData != None else 0
  475. resFinish=CountInListNot(taskMainData,"",20)
  476. yresALL=len(YtaskMainData) if YtaskMainData != None else 0
  477. yresFinish=CountInListNot(YtaskMainData,"",20)
  478. return(resALL, resFinish,yresALL,yresFinish)
  479. def function3(startTime,res):
  480. list=[]
  481. ress={}
  482. aa=30#准备时间
  483. bb=25#收尾时间
  484. if len(res) !=0 and res !=None:
  485. for i in res:
  486. #print(i)
  487. if i[3]== "航前":
  488. a=("航前",datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)- datetime.timedelta(minutes=aa),datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(minutes=90)+ datetime.timedelta(minutes=bb),i[5])
  489. elif i[3]== "短停接":
  490. a = ("短停接", datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)- datetime.timedelta(minutes=aa), datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=15)+ datetime.timedelta(minutes=bb),i[5])
  491. elif i[3]== "特后前接":
  492. a = ("特后前接", datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)- datetime.timedelta(minutes=aa), datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=15)+ datetime.timedelta(minutes=bb),i[5])
  493. elif i[3]== "短停送":
  494. a = ("短停送", datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)- datetime.timedelta(minutes=aa), datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=25)+ datetime.timedelta(minutes=bb),i[5])
  495. elif i[3]== "特后前送":
  496. a = ("特后前送", datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)- datetime.timedelta(minutes=aa), datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=25)+ datetime.timedelta(minutes=bb),i[5])
  497. else:
  498. a = ("航后", datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") - datetime.timedelta(minutes=5)- datetime.timedelta(minutes=aa), datetime.datetime.strptime(i[2], "%Y-%m-%d %H:%M:%S") + datetime.timedelta(minutes=120)+ datetime.timedelta(minutes=bb),i[5])
  499. list.append(a)
  500. for j in range(0,66): #1980 /间隔
  501. judgeTime=startTime + datetime.timedelta(minutes=30*j)
  502. tr=0
  503. prf=0
  504. pof=0
  505. taf=0
  506. ytr = 0 #预测
  507. yprf = 0
  508. ypof = 0
  509. ytaf = 0
  510. if list !=[]:
  511. for ii in list:
  512. if ii[1] < judgeTime < ii[2] and ii[3] != "2" and judgeTime < datetime.datetime.now():
  513. if ii[0]== "航前":
  514. prf+=1
  515. elif ii[0]== "短停接":
  516. tr+=1
  517. elif ii[0]== "特后前接":
  518. taf+=1
  519. elif ii[0]== "短停送":
  520. tr+=1
  521. elif ii[0]== "特后前送":
  522. taf+=1
  523. else:
  524. pof+=1
  525. if ii[1] < judgeTime < ii[2]:
  526. if ii[0] == "航前":
  527. yprf += 1
  528. elif ii[0] == "短停接":
  529. ytr+=1
  530. elif ii[0] == "特后前接":
  531. ytaf+=1
  532. elif ii[0]== "短停送":
  533. ytr+=1
  534. elif ii[0]== "特后前送":
  535. ytaf+=1
  536. else:
  537. ypof+=1
  538. ress["%s"%judgeTime]={"航前":prf,"短停":tr,"特后前":taf,"航后":pof,"合计":prf+tr+taf+pof,"预计航前":yprf,"预计短停":ytr,"预计特后前":ytaf,"预计航后":ypof,"预计合计":yprf+ytr+ytaf+ypof}
  539. return ress
  540. def function5():#随机任务
  541. now = datetime.datetime.now()
  542. nowDay = datetime.date.today().strftime("%Y%m%d")
  543. nowDay_1 = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d")
  544. peopleSchedule=DataDBUtilsgetData("peopleSchedule%s" % nowDay, "*", "附加消息 like '%随机离港%'")
  545. ypeopleSchedule = DataDBUtilsgetData("peopleSchedule%s" % nowDay_1, "*", "附加消息 like '%随机离港%'")
  546. res=function6(peopleSchedule,nowDay)
  547. yres = function6(ypeopleSchedule, nowDay_1)
  548. return(res,len(peopleSchedule),yres,len(ypeopleSchedule))
  549. def function6(res,day):
  550. a=0
  551. if res != None and len(res) !=0:
  552. for i in res:
  553. check=DataDBUtilsgetData("sortFlight%s" % day, "级别", "编号 ='%s'" % (i[1] + "-2"))
  554. if check !=None and len(check) != 0 and check[0][0] == "4":
  555. a+=1
  556. return a
  557. def function7():#航材工具
  558. now = datetime.datetime.now()
  559. startTime = now.replace(hour=0, minute=0, second=0, microsecond=0)
  560. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  561. tstartTime = (now + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  562. resALL=getData("sendTaskList",'*',"'%s' < 配送发起时间 and 配送发起时间 <'%s'"%(startTime,tstartTime))
  563. yresALL = getData("sendTaskList", '*', "'%s' < 配送发起时间 and 配送发起时间 <'%s'" % (ystartTime, startTime))
  564. res=function8(resALL)
  565. yres = function8(yresALL)
  566. return(res,yres)
  567. #
  568. def function8(res):
  569. ress={}
  570. if res !=None and len(res) !=0:
  571. for i in res:
  572. if i[23] == "" and i[6] != "":
  573. costtime= math.ceil((datetime.datetime.strptime(i[23].split(".")[0], "%Y-%m-%d %H:%M:%S")- datetime.datetime.strptime(i[6].split(".")[0], "%Y-%m-%d %H:%M:%S")).total_seconds()/60)
  574. else:
  575. costtime=""
  576. ress[i[16]]={"类型":i[2],"机位":i[17],"配送发起时间":i[4].split(".")[0],"耗时":costtime,"任务级别":i[13],"任务号":i[16]}
  577. return ress
  578. def function9():#二拖
  579. now = datetime.datetime.now()
  580. startTime = now.replace(hour=0, minute=0, second=0, microsecond=0)
  581. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  582. tstartTime = (now + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  583. resALL = getData("towbarMain", '*', "'%s' < 创建时间 and 创建时间 <'%s'" % (startTime, tstartTime))
  584. yresALL = getData("towbarMain", '*', "'%s' < 创建时间 and 创建时间 <'%s'" % (ystartTime, startTime))
  585. res=function10(resALL)
  586. yres = function10(yresALL)
  587. return(res,yres)
  588. def function10(res):
  589. ress={}
  590. if res !=None and len(res) !=0:
  591. for i in res:
  592. if i[11] !="":
  593. costtime= math.ceil((datetime.datetime.strptime(i[11].split(".")[0], "%Y-%m-%d %H:%M:%S")- datetime.datetime.strptime(i[9].split(".")[0], "%Y-%m-%d %H:%M:%S")).total_seconds()/60)
  594. else:
  595. costtime=""
  596. ress[i[12]]={"创建时间":i[8].split(".")[0],"耗时":costtime,"任务号":i[12]}
  597. return ress
  598. def initFlightDatabase1(datatime):
  599. database = flightDB(host=online_host,
  600. port=online_port,
  601. user=user1,
  602. password=online_password,
  603. database=databasefileDB
  604. )
  605. try:
  606. dataListDic = {}
  607. primaryKey = 'SERIAL PRIMARY KEY'
  608. for key8 in list(dataListLabel)[1:]:
  609. dataListDic[key8] = 'text not null'
  610. database.initTable('dataList{}'.format(datatime), "序号", primaryKey, dataListDic)
  611. database.close()
  612. except Exception:
  613. database.close()
  614. print(traceback.format_exc())
  615. def getData(tablename, data, key):
  616. fdb = flightDB(host=host,
  617. port=port,
  618. user=user1,
  619. password=password,
  620. database=databasefileDB
  621. )
  622. try:
  623. res = fdb.queryTabel(tablename, data, key)
  624. fdb.close()
  625. return res
  626. except Exception:
  627. fdb.close()
  628. print(traceback.format_exc())
  629. return []
  630. def DataDBUtilsgetData(tablename,data,key):
  631. fdb = flightDB(host=host,
  632. port=port,
  633. user=user1,
  634. password=password,
  635. database=flightDatedb,
  636. )
  637. try:
  638. res = fdb.queryTabel(tablename, data, key)
  639. fdb.close()
  640. return res
  641. except Exception:
  642. fdb.close()
  643. print(traceback.format_exc())
  644. return []