DataComputer.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. alldata=DataDBUtilsgetData("sortFlight%s" % nowDay, "*", "编号 != ''")
  280. Yalldata=DataDBUtilsgetData("sortFlight%s" % nowDay_1, "*", "编号 != ''")
  281. try:
  282. mytask1 = function1(alldata,Yalldata)
  283. finishdeTask=finishdeTask+"task1/"
  284. except:
  285. mytask1=[]
  286. pass
  287. try:
  288. mytask2 = function2(alldata,Yalldata)
  289. finishdeTask=finishdeTask+"task2/"
  290. except:
  291. mytask2 = []
  292. pass
  293. now = datetime.datetime.now()
  294. startTime = now.replace(hour=0, minute=0, second=0, microsecond=0)
  295. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  296. tstartTime = (now + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  297. taskMainData=getData("taskMain", "*", "'%s' < 任务开始时间 and 任务开始时间 <'%s'"%(startTime,tstartTime))
  298. YtaskMainData = getData("taskMain", "*", "'%s' < 任务开始时间 and 任务开始时间 <'%s'" % (ystartTime, startTime))
  299. try:
  300. mytask3 = function4(taskMainData,YtaskMainData)
  301. finishdeTask=finishdeTask+"task3/"
  302. except:
  303. mytask3=[]
  304. pass
  305. try:
  306. mytask4 = function5()
  307. finishdeTask=finishdeTask+"task4/"
  308. except:
  309. pass
  310. try:
  311. mytask5 = function7()
  312. finishdeTask=finishdeTask+"task5/"
  313. except:
  314. pass
  315. try:
  316. mytask6 = function9()
  317. finishdeTask=finishdeTask+"task6/"
  318. except:
  319. pass
  320. nowday=datetime.date.today()
  321. nowday_1 = datetime.date.today() - datetime.timedelta(days=1)
  322. dy={0:"每日短停",1:"每日航前",2:"每日航后",3:"每日特后前",4:"每日停场",5:"每日短停",6:"每日航前",7:"每日航后",8:"每日特后前",9:"每日停场",10:"每日外委",11:"每日外委",12:"每日总数",13:"每日总数",14:"每日川航",15:"每日川航",16:"已执行",17:"已执行"}
  323. fdb = flightDB(host=online_host,
  324. port=online_port,
  325. user=online_user,
  326. password=online_password,
  327. database=databasefileDB
  328. )
  329. try:
  330. olddata_1=fdb.getAlldata("dataList{}".format(nowDay_1))
  331. except:
  332. olddata_1=[]
  333. try:
  334. olddata_2=fdb.getAlldata("dataList{}".format(nowDay_2))
  335. except:
  336. olddata_2=[]
  337. fdb.lazydeleteTable("dataList{}".format(nowDay_1),"1=1")
  338. fdb.lazydeleteTable("dataList{}".format(nowDay), "1=1")
  339. try:
  340. for ii in range(0,len(mytask1)): ##每日航班分布
  341. if ii in [5,6,7,8,9,11,13,15,17]:
  342. res_data_1=TuplefindInDataList(olddata_2,dy[ii],mytask1[ii],1)
  343. newdic={"类型":dy[ii],"时间":nowday_1,"数据1":res_data_1,"数据2":"",'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  344. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  345. else:
  346. res_data=TuplefindInDataList(olddata_1,dy[ii],mytask1[ii],1)
  347. newdic = {"类型": dy[ii], "时间": nowday, "数据1": res_data, "数据2": "", '唯一序列': "", '备1': "", '备2': "",'备3': "", '备4': "", '备5': "", '备6': ""}
  348. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  349. for ii in mytask2[0].keys():##每刻航班分布
  350. for iii in mytask2[0][ii].keys():
  351. res_data = TuplefindInDataList2(olddata_1, '每刻%s'%iii,mytask2[0][ii][iii],1, ii,2)
  352. newdic={"类型":'每刻%s'%iii,"时间":ii,"数据1":res_data,"数据2":"",'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  353. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  354. for iiii in mytask2[1].keys():
  355. for iiiii in mytask2[1][iiii].keys():
  356. res_data = TuplefindInDataList2(olddata_2, '每刻%s'%iiiii, mytask2[1][iiii][iiiii],1, iiii,2)
  357. newdic={"类型":'每刻%s'%iiiii,"时间":iiii,"数据1":res_data,"数据2":"",'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  358. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  359. #每日任务分布
  360. res_data_1 = TuplefindInDataList(olddata_1, '任务分布', mytask3[1], 1)
  361. res_data_2 = TuplefindInDataList(olddata_1, '任务分布', mytask3[0], 1)
  362. newdic={"类型":'任务分布',"时间":nowday,"数据1":res_data_1,"数据2":res_data_2,'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  363. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  364. res_data_1 = TuplefindInDataList(olddata_2, '任务分布', mytask3[3], 1)
  365. res_data_2 = TuplefindInDataList(olddata_2, '任务分布', mytask3[2], 1)
  366. newdic = {"类型": '任务分布', "时间": nowday_1, "数据1": res_data_1, "数据2": res_data_2, '唯一序列': "", '备1': "", '备2': "",'备3': "", '备4': "", '备5': "", '备6': ""}
  367. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  368. #随机任务
  369. res_data_1 = TuplefindInDataList(olddata_1, '随机任务', mytask4[0], 1)
  370. res_data_2 = TuplefindInDataList(olddata_1, '随机任务', mytask4[1], 1)
  371. newdic={"类型":'随机任务',"时间":nowday,"数据1":res_data_1,"数据2":res_data_2,'唯一序列':"",'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  372. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  373. res_data_1 = TuplefindInDataList(olddata_2, '随机任务', mytask4[2], 1)
  374. res_data_2 = TuplefindInDataList(olddata_2, '随机任务', mytask4[3], 1)
  375. newdic = {"类型": '随机任务', "时间": nowday_1, "数据1":res_data_1,"数据2":res_data_2, '唯一序列': "", '备1': "", '备2': "",'备3': "", '备4': "", '备5': "", '备6': ""}
  376. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  377. #航材工具配送
  378. for i in mytask5[0].keys():
  379. 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':""}
  380. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  381. for i in mytask5[1].keys():
  382. 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':""}
  383. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  384. #二拖
  385. for i in mytask6[0].keys():
  386. newdic={"类型":'二拖任务',"时间":mytask6[0][i]['创建时间'],"数据1":"","数据2":mytask6[0][i]['耗时'],'唯一序列':mytask6[0][i]['任务号'],'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  387. fdb.lazyInsertData("dataList{}".format(nowDay), newdic)
  388. for i in mytask6[1].keys():
  389. newdic={"类型":'二拖任务',"时间":mytask6[1][i]['创建时间'],"数据1":"","数据2":mytask6[1][i]['耗时'],'唯一序列':mytask6[1][i]['任务号'],'备1':"",'备2':"",'备3':"",'备4':"",'备5':"",'备6':""}
  390. fdb.lazyInsertData("dataList{}".format(nowDay_1), newdic)
  391. fdb.FunctionCommit()
  392. fdb.close()
  393. #t3 = datetime.datetime.now()
  394. #print(t3 - t2)
  395. print(datetime.datetime.now(), "[计算中心]统计分析写入完毕(%s)"%finishdeTask)
  396. return "ok"
  397. except Exception as e:
  398. print(traceback.format_exc())
  399. fdb.close()
  400. return "fail"
  401. def TuplefindInList(lists: list, args, numb): # 返回列表
  402. res = []
  403. try:
  404. for l in lists:
  405. if args == l[numb]:
  406. res.append(l)
  407. return res
  408. except:
  409. return res
  410. def CountAllList(lists: list): # 返回列表
  411. res = 0
  412. try:
  413. for l in lists:
  414. res+=1
  415. return res
  416. except:
  417. return res
  418. def CountInList(lists: list, args, numb): # 返回列表
  419. res = 0
  420. try:
  421. for l in lists:
  422. if args in l[numb]:
  423. res+=1
  424. return res
  425. except:
  426. return res
  427. def CountInListNot(lists: list, args, numb): # 返回列表
  428. res = 0
  429. try:
  430. for l in lists:
  431. if l[numb] != args:
  432. res+=1
  433. return res
  434. except:
  435. return res
  436. def CountFinshed(lists: list): # 返回列表
  437. res = 0
  438. try:
  439. for l in lists:
  440. if l[3] != "停场" and (l[5] == "3" or l[5] == "4"):
  441. res+=1
  442. return res
  443. except:
  444. return res
  445. def function1(alldata,Yalldata): #查询每日航班的分布
  446. resTR=CountInList(alldata, "短停", 3)
  447. resPEF=CountInList(alldata, "航前", 3)
  448. resPOF=CountInList(alldata, "航后", 3)
  449. resTAF=CountInList(alldata, "特后前", 3)
  450. resST=CountInList(alldata, "停场", 3)
  451. resAll=resTR+resPEF+resPOF+resTAF
  452. resfinsh=CountFinshed(alldata)
  453. YresTR=CountInList(Yalldata, "短停", 3)
  454. YresPEF=CountInList(Yalldata, "航前", 3)
  455. YresPOF=CountInList(Yalldata, "航后", 3)
  456. YresTAF=CountInList(Yalldata, "特后前", 3)
  457. YresST=CountInList(Yalldata, "停场", 3)
  458. YreAll=YresTR+YresPEF+YresPOF+YresTAF
  459. ww=CountInList(alldata, "PB", 0)
  460. yww=CountInList(Yalldata, "PB", 0)
  461. ch=resAll-ww
  462. Ych=YreAll-yww
  463. Yresfinsh=CountFinshed(Yalldata)
  464. return (resTR,resPEF,resPOF,resTAF,resST,YresTR,YresPEF,YresPOF,YresTAF,YresST,ww,yww,resAll,YreAll,ch,Ych,resfinsh,Yresfinsh)
  465. def function2(alldata,Yalldata): #实时任务分布
  466. now=datetime.datetime.now()
  467. startTime = now.replace(hour=0,minute=0, second=0, microsecond=0)
  468. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  469. res=function3(startTime,alldata)
  470. yres = function3(ystartTime, Yalldata)
  471. return(res,yres)
  472. def function4(taskMainData,YtaskMainData):#任务分布
  473. resALL=len(taskMainData) if taskMainData != None else 0
  474. resFinish=CountInListNot(taskMainData,"",20)
  475. yresALL=len(YtaskMainData) if YtaskMainData != None else 0
  476. yresFinish=CountInListNot(YtaskMainData,"",20)
  477. return(resALL, resFinish,yresALL,yresFinish)
  478. def function3(startTime,res):
  479. list=[]
  480. ress={}
  481. aa=30#准备时间
  482. bb=25#收尾时间
  483. if len(res) !=0 and res !=None:
  484. for i in res:
  485. #print(i)
  486. if i[3]== "航前":
  487. 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])
  488. elif i[3]== "短停接":
  489. 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])
  490. elif i[3]== "特后前接":
  491. 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])
  492. elif i[3]== "短停送":
  493. 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])
  494. elif i[3]== "特后前送":
  495. 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])
  496. else:
  497. 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])
  498. list.append(a)
  499. for j in range(0,66): #1980 /间隔
  500. judgeTime=startTime + datetime.timedelta(minutes=30*j)
  501. tr=0
  502. prf=0
  503. pof=0
  504. taf=0
  505. ytr = 0 #预测
  506. yprf = 0
  507. ypof = 0
  508. ytaf = 0
  509. if list !=[]:
  510. for ii in list:
  511. if ii[1] < judgeTime < ii[2] and ii[3] != "2" and judgeTime < datetime.datetime.now():
  512. if ii[0]== "航前":
  513. prf+=1
  514. elif ii[0]== "短停接":
  515. tr+=1
  516. elif ii[0]== "特后前接":
  517. taf+=1
  518. elif ii[0]== "短停送":
  519. tr+=1
  520. elif ii[0]== "特后前送":
  521. taf+=1
  522. else:
  523. pof+=1
  524. if ii[1] < judgeTime < ii[2]:
  525. if ii[0] == "航前":
  526. yprf += 1
  527. elif ii[0] == "短停接":
  528. ytr+=1
  529. elif ii[0] == "特后前接":
  530. ytaf+=1
  531. elif ii[0]== "短停送":
  532. ytr+=1
  533. elif ii[0]== "特后前送":
  534. ytaf+=1
  535. else:
  536. ypof+=1
  537. ress["%s"%judgeTime]={"航前":prf,"短停":tr,"特后前":taf,"航后":pof,"合计":prf+tr+taf+pof,"预计航前":yprf,"预计短停":ytr,"预计特后前":ytaf,"预计航后":ypof,"预计合计":yprf+ytr+ytaf+ypof}
  538. return ress
  539. def function5():#随机任务
  540. now = datetime.datetime.now()
  541. nowDay = datetime.date.today().strftime("%Y%m%d")
  542. nowDay_1 = (datetime.date.today() - datetime.timedelta(days=1)).strftime("%Y%m%d")
  543. peopleSchedule=DataDBUtilsgetData("peopleSchedule%s" % nowDay, "*", "附加消息 like '%随机离港%'")
  544. ypeopleSchedule = DataDBUtilsgetData("peopleSchedule%s" % nowDay_1, "*", "附加消息 like '%随机离港%'")
  545. res=function6(peopleSchedule,nowDay)
  546. yres = function6(ypeopleSchedule, nowDay_1)
  547. return(res,len(peopleSchedule),yres,len(ypeopleSchedule))
  548. def function6(res,day):
  549. a=0
  550. if res != None and len(res) !=0:
  551. for i in res:
  552. check=DataDBUtilsgetData("sortFlight%s" % day, "级别", "编号 ='%s'" % (i[1] + "-2"))
  553. if check !=None and len(check) != 0 and check[0][0] == "4":
  554. a+=1
  555. return a
  556. def function7():#航材工具
  557. now = datetime.datetime.now()
  558. startTime = now.replace(hour=0, minute=0, second=0, microsecond=0)
  559. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  560. tstartTime = (now + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  561. resALL=getData("sendTaskList",'*',"'%s' < 配送发起时间 and 配送发起时间 <'%s'"%(startTime,tstartTime))
  562. yresALL = getData("sendTaskList", '*', "'%s' < 配送发起时间 and 配送发起时间 <'%s'" % (ystartTime, startTime))
  563. res=function8(resALL)
  564. yres = function8(yresALL)
  565. return(res,yres)
  566. #
  567. def function8(res):
  568. ress={}
  569. if res !=None and len(res) !=0:
  570. for i in res:
  571. if i[23] == "" and i[6] != "":
  572. 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)
  573. else:
  574. costtime=""
  575. ress[i[16]]={"类型":i[2],"机位":i[17],"配送发起时间":i[4].split(".")[0],"耗时":costtime,"任务级别":i[13],"任务号":i[16]}
  576. return ress
  577. def function9():#二拖
  578. now = datetime.datetime.now()
  579. startTime = now.replace(hour=0, minute=0, second=0, microsecond=0)
  580. ystartTime = (now - datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  581. tstartTime = (now + datetime.timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
  582. resALL = getData("towbarMain", '*', "'%s' < 创建时间 and 创建时间 <'%s'" % (startTime, tstartTime))
  583. yresALL = getData("towbarMain", '*', "'%s' < 创建时间 and 创建时间 <'%s'" % (ystartTime, startTime))
  584. res=function10(resALL)
  585. yres = function10(yresALL)
  586. return(res,yres)
  587. def function10(res):
  588. ress={}
  589. if res !=None and len(res) !=0:
  590. for i in res:
  591. if i[11] !="":
  592. 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)
  593. else:
  594. costtime=""
  595. ress[i[12]]={"创建时间":i[8].split(".")[0],"耗时":costtime,"任务号":i[12]}
  596. return ress
  597. def initFlightDatabase1(datatime):
  598. database = flightDB(host=online_host,
  599. port=online_port,
  600. user=user1,
  601. password=online_password,
  602. database=databasefileDB
  603. )
  604. try:
  605. dataListDic = {}
  606. primaryKey = 'SERIAL PRIMARY KEY'
  607. for key8 in list(dataListLabel)[1:]:
  608. dataListDic[key8] = 'text not null'
  609. database.initTable('dataList{}'.format(datatime), "序号", primaryKey, dataListDic)
  610. database.close()
  611. except Exception:
  612. database.close()
  613. print(traceback.format_exc())
  614. def getData(tablename, data, key):
  615. fdb = flightDB(host=host,
  616. port=port,
  617. user=user1,
  618. password=password,
  619. database=databasefileDB
  620. )
  621. try:
  622. res = fdb.queryTabel(tablename, data, key)
  623. fdb.close()
  624. return res
  625. except Exception:
  626. fdb.close()
  627. print(traceback.format_exc())
  628. return []
  629. def DataDBUtilsgetData(tablename,data,key):
  630. fdb = flightDB(host=host,
  631. port=port,
  632. user=user1,
  633. password=password,
  634. database=flightDatedb,
  635. )
  636. try:
  637. res = fdb.queryTabel(tablename, data, key)
  638. fdb.close()
  639. return res
  640. except Exception:
  641. fdb.close()
  642. print(traceback.format_exc())
  643. return []