2017-12-26 18 views
0

나는 텍스트 파일을 업로드 한 다음 사용자 입력을 제공하고 사용자 입력 처리에 따라 시나리오를 추가합니다.사용자 입력에 대한 프로세스 데이터

샘플 파일 :

DOWN 07.09.2016 08:21:33 - 07.09.2016 08:23:33 
UP 07.11.2016 09:41:07 - 09.11.2016 09:20:33 
DOWN 09.11.2016 08:26:33 - 09.11.2016 08:46:33 
UP 09.11.2016 08:23:33 - 09.11.2016 08:25:33 
DOWN 09.11.2016 08:36:33 - 09.11.2016 08:41:33 
DOWN 10.11.2016 08:36:33 - 10.11.2016 08:39:33 

코드 : 코드 위

try: 
    import Tkinter as Tk 
    import tkFileDialog as fileDialog 
except ImportError: 
    import tkinter as Tk 
    import tkinter.filedialog as fileDialog 

import datetime 



def read_data(): 
    ''' 
    Read data from file and convert to list with datetime 
    which can be used to calculate time and display. 
    ''' 
    global data 

    filename = fileDialog.askopenfilename() 

    if filename: 
     # read all lines 
     with open(filename) as fileHandle: 
      lines = fileHandle.readlines() 

     # convert to `datetime` (not `timestamp`) 
     data = []   
     for line in lines: 
      #direction = line[:4].strip() 
      #dt1 = line[5:24] 
      #dt2 = line[27:46] 

      direction, d1, t1, _, d2, t2 = line.split() 
      dt1 = d1 + ' ' + t1 
      dt2 = d2 + ' ' + t2 

      t1 = datetime.datetime.strptime(dt1, "%d.%m.%Y %H:%M:%S") 
      t2 = datetime.datetime.strptime(dt2, "%d.%m.%Y %H:%M:%S") 

      seconds = (t2-t1).seconds 

      data.append([direction, t1, t2, seconds]) 

     print(data) 


def processText(lines, selected_date): 

    total = 0 
    start = None 

    print(selected_date) 
    # if there is `selected_date` then convert to `datetime` 
    if selected_date: 
     try: 
      selected_date = datetime.datetime.strptime(selected_date, "%d.%m.%Y") 
     except AttributeError as ex: 
      print("ERROR:", ex) 
      selected_date = None 

    # calculate time 
    for direction, t1, t2, seconds in lines: 

     if direction == "DOWN": 

      # if `selected_date` then filter times 
      if selected_date and t1 <= selected_date: 
       continue 

      if not start: 
       start = t1.strftime("%d.%m.%Y %H:%M:%S") 

      total += seconds 

    # convert to minutes after summing all second 
    total = total//60 

    return total, start 

def calculate(): 

    all_dates = entry.get().split(',') 
    print(all_dates) 
    all_dates = [date.strip() for date in all_dates] 

    txt = '' 

    for current_date in all_dates: 
     down, start = processText(data, current_date) 
     txt += "Total Downtime is {0} min from {1}\n".format(down, start) 

    textVar.set(txt) 

# --- main --- 

data = None # to keep data from file 

# - 

root = Tk.Tk() 

button = Tk.Button(root, text="Open", command=read_data) 
button.grid(column=1, row=1) 

textVar = Tk.StringVar(root) 

label = Tk.Label(root, textvariable=textVar) 
label.grid(column=1, row=2) 

entry = Tk.Entry(root) 
entry.grid(column=1, row=3) 

button2 = Tk.Button(root, text="Calculate", command=calculate) 
button2.grid(column=1, row=4) 

root.mainloop() 

포맷 Date1.Month1.Year1, Date2.Month2.Year2에서 날짜를 선택할 것인지 묻는 확인 팝업 (에 따라 .

Total Downtime is x min from date1.month1.year1 xx:xx:xx(time1) 
Total Downtime is y min from date2.month2.year2 yy:yy:yy(time2) 
,536 : 날짜 숫자 입력)

과 같은 출력을 리턴

여기 분당 가동 중지 시간에 대한 세부 정보가 있으며 날짜까지 백분율로 변환하고 싶습니다. 예를 들어 ->

사용자 입력 :

1.9.2016,1.11.2016,1.1.2016

출력 : 가용성 계산 뒤에

Total Downtime is 30 min from 1.9.2016 08:21:33 & Availability percentage from selected date to till date : xx.xxx% 
Total Downtime is 28 min from 1.11.2016 08:26:33 & Availability percentage from selected date to till date : yy.yyy% 
Total Downtime is 30 min from 1.11.2016 08:26:33 & Availability percentage from selected date to till date : zz.zzz% 

논리는 것

total number of min down from date(which is retrieved)/total number of min till date * 100 

나는이 부분에 갇혀있다. 달성 할 수 있는가? 어떤 도움이 좋을지 !! 대신 날짜 NoneprocessText()를 실행하면 아래

total_down, start = processText(data, None) 

+0

그렇습니다 달성 - 먼저 모든 분을 추가해야합니다. 분을 추가하는 데 문제가 있습니까? BTW : 만약'processText()'를'selected_date' 대신'None'으로 실행하면 "전체 분 수"를 얻습니다. 그런 다음 "선택한 날짜의 총 시간"을 빼서 "선택한 날짜까지 전체 시간 (분)"을 얻으십시오. – furas

+0

다음과 같이 [Minimal, Complete, Verifiable example] (https://stackoverflow.com/help/mcve) 대신 [ 전체 코드. – Nae

+0

예, 선택한 날짜까지 총 시간 (분)을 얻으려면 어떻게해야하는지 모르겠습니다. – vanishka

답변

1

는 당신이 분의 총 수를 얻을 당신은 비율을 계산하는 데 사용할 수 있습니다.

percentage = (down/total_down) * 100 

당신이 분의 총 수를 원하는 경우 그 다음 아래로 또는 위로 때 당신은 점

def calculate(): 

    all_dates = entry.get().split(',') 
    print(all_dates) 
    all_dates = [date.strip() for date in all_dates] 

    # calculate total number of minutes when it was down 
    total_down, start = processText(data, None) # <-- None 

    print('total_down:', total_down) 

    txt = '' 

    for current_date in all_dates: 
     down, start = processText(data, current_date) 

     # calculate percetage 
     percentage = (down/total_down) * 100 

     # use string formatting {:.2f} to display only two digits after dot 
     txt += "Total Downtime is {} min from {} ({:.2f}%)\n".format(down, start, percentage) 

    textVar.set(txt) 

enter image description here


후 두 자리 숫자를 표시하는 {:.2f}를 포맷 문자열을 사용할 수 있습니다 processText을 변경하고 새 매개 변수 (예 : word)를 추가하여 direction이 맞는지 확인해야합니다. DOWN 또는 UP 또는 둘 다 (word = None)

def processText(lines, selected_date, word="DOWN"): 

    total = 0 
    start = None 

    print(selected_date) 
    # if there is `selected_date` then convert to `datetime` 
    if selected_date: 
     try: 
      selected_date = datetime.datetime.strptime(selected_date, "%d.%m.%Y") 
     except AttributeError as ex: 
      print("ERROR:", ex) 
      selected_date = None 

    # calculate time 
    for direction, t1, t2, seconds in lines: 

     if not word or word == direction: 

      # if `selected_date` then filter times 
      if selected_date and t1 <= selected_date: 
       continue 

      if not start: 
       start = t1.strftime("%d.%m.%Y %H:%M:%S") 

      total += seconds 

    # convert to minutes after summing all second 
    total = total//60 

    return total, start 

def calculate(): 

    all_dates = entry.get().split(',') 
    print(all_dates) 
    all_dates = [date.strip() for date in all_dates] 

    # calculate total number of minutes when it was down and up 
    total_down, start = processText(data, None, None) 

    print('total_down:', total_down) 

    txt = '' 

    for current_date in all_dates: 
     down, start = processText(data, current_date, "DOWN") 
     percentage = (down/total_down) * 100 
     txt += "Total Downtime is {} min from {} ({:.2f}%)\n".format(down, start, percentage) 

    textVar.set(txt) 
+0

어떤 O/P도 제공하지 않습니다. 어떤 에러도 없습니다. – vanishka

+0

코드를 봅니다. -'total_down'을 계산하고 나중에이 값을 사용하여'percentage'를 계산하고'{:.2f}'를 사용하여 점 뒤에 두 자리 숫자로 백분율을 표시합니다. – furas

+0

여기에 날짜를 선택했습니다> 12.9.2016 이것은 다운 타임을 2.07 %로 제공하지만 계산 논리에 따르면 99.07 %의 – vanishka