我有一个场景,我上传文本文件,然后提供用户输入,然后根据用户输入处理进一步。
示例文件:
DOWN 07.11.2016 08:21:33 - 07.11.2016 08:22: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:35: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:38:33
DOWN 10.11.2016 08:36:33 - 10.11.2016 08:38:33
代码:
try:
import Tkinter as Tk
import tkFileDialog as fileDialog
except ImportError:
import tkinter as Tk
fileDialog = Tk.filedialog
import datetime
def user_input():
current_date = my_entry.get()
def processText(lines):
total = 0
start = None
for k, line in enumerate(lines):
direction, date1, time1, _, date2, time2 = line.split()
if direction != "Down": continue
if start==None: start = date1 + ' ' + time1
# 1
D1, M1, Y1 = date1.split('.')
h1, m1, s1 = time1.split(':')
# 2
D2, M2, Y2 = date2.split('.')
h2, m2, s2 = time2.split(':')
# Timestamps
t1 = datetime.datetime(*map(int, [Y1, M1, D1, h1, m1, s1])).timestamp()
t2 = datetime.datetime(*map(int, [Y2, M2, D2, h2, m2, s2])).timestamp()
total += (t2-t1)
return total, start
def openFile():
filename = fileDialog.askopenfilename()
fileHandle = open(filename, 'r')
down, start = processText(fileHandle.readlines())
txt = "Total Downtime is {0} min from {1}".format(down//60, start)
textVar.set(txt)
fileHandle.close()
root = Tk.Tk()
button = Tk.Button(root, text="Open", command=openFile)
button.grid(column=1, row=1)
textVar = Tk.StringVar(root)
label = Tk.Label(root, textvariable=textVar)
label.grid(column=1, row=2)
root.mainloop()
上面给出了输出总停机时间
12 min from 07.11.2016 08:21:33
但是在这里我试图介绍DATE的用户输入,例如,如果我想从09.11.2016获得停机时间,那么它应该提示我选择日期和输出(总停机时间)应该来自所选日期
任何帮助都会很棒!!
编辑1(添加了o / p):
追溯:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/angelina/Desktop/test2/tinkteruser.py", line 34, in read_data
t1 = datetime.datetime.strptime(dt1, "%d.%m.%Y %H:%M:%S")
File "C:\Program Files (x86)\Python36-32\lib\_strptime.py", line 565, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Program Files (x86)\Python36-32\lib\_strptime.py", line 362, in _strptime
(data_string, format))
ValueError: time data 'able 22.06.2017 1' does not match format '%d.%m.%Y %H:%M:%S
答案 0 :(得分:3)
您可以阅读一次文件并计算不同的日期。
btw:作为扩展程序,它可以在Entry
中添加几个日期(以空格或逗号分隔)并为每个日期计算total
,或者在两个日期的范围内计算
在read_data()
中,它会加载所有数据并使用
datetime.datetime.strptime(date1 + ' ' + time1, "%d.%m.%Y %H:%M:%S")
在calculate
中,它从Entry
获取数据,并使用文件和日期中的数据执行processText()
。
它将包含Entry
数据的字符串转换为datetime
。字符串可能包含不正确的日期或格式不正确,因此我使用try/except
。
使用t1 <= selected_date
比较两个datetime
。
使用(t2-t1).seconds
获取两个日期之间的秒数(不使用timestamp()
)。它甚至可以在read_data()
中执行此操作。
完整代码:
问题可能是except Exception as ex:
,这在Python 2中是不正确的。
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, date1, time1, _, date2, time2 = line.split()
t1 = datetime.datetime.strptime(date1 + ' ' + time1, "%d.%m.%Y %H:%M:%S")
t2 = datetime.datetime.strptime(date2 + ' ' + time2, "%d.%m.%Y %H:%M:%S")
data.append([direction, t1, t2])
print(data)
def processText(lines, selected_date):
total = 0
start = None
# if there is `selected_date` then convert to `datetime`
if selected_date:
try:
selected_date = datetime.datetime.strptime(selected_date, "%d.%m.%Y")
except Exception as ex:
print("ERROR:", ex)
selected_date = None
# calculate time
for direction, t1, t2 in lines:
if direction == "DOWN":
# if `selected_date` then filter times
if selected_date and t1 <= selected_date:
continue
if not start:
start = t1
total += (t2-t1).seconds//60
return total, start.strftime("%d.%m.%Y %H:%M:%S")
def calculate():
current_date = entry.get().strip()
down, start = processText(data, current_date)
txt = "Total Downtime is {0} min from {1}".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()
编辑:其他更改(保留以前的版本进行比较)
现在计算(t2-t1).seconds
中的read_data
并将其保存在data
它在添加所有秒数后转换为分钟,因此它可以提供更多的分钟。
现在它可以计算条目中的许多日期(以逗号分隔)。
它还使用slicing
从行中获取元素
我假设所有数据的格式都与样本文件类似。
DOWN 07.11.2016 08:21:33 - 07.11.2016 08:22: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:35: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:38:33
DOWN 10.11.2016 08:36:33 - 10.11.2016 08:38:33
编辑:似乎文件的值可能比"DOWN"
和"UP "
更长,因此切片不起作用,因此我再次使用split()
代替{{1 }}
slicing