首页 > 解决方案 > 循环用数据做奇怪的事情

问题描述

好的,所以我已经在这个问题上工作了大约 8 个小时,但我无法弄清楚发生了什么。所以我正在制作的应用程序是一个使用 android 应用程序的 TimeSheet 管理器;我在 python 中制作的桌面应用程序;和一个 MySQL 数据库。桌面应用程序几乎只使用数据库上的查询。因此,当前查询是让用户检查员工在两个日期之间完成的小时数:

query = "SELECT FirstName, LastName, StartTime, FinishTime FROM Sheets WHERE DateTesting >= '"+StartDate+"' AND DateTesting <= '"+EndDate+"';"

然后 python 应用程序通过使用日期时间来显示结果,以获取开始时间和结束时间并计算出员工工作的小时数。这工作正常。

        tdelta = datetime.datetime.strptime(s2, FMT) - datetime.datetime.strptime(s1, FMT)
        tdelta=(str(tdelta))
        totalDelta.append(tdelta)

        self.labels.append(Label(myframe,text=f'Name: {a} {b} | Start Time: {c} | Finish Time: {d} | Hours Done: {tdelta}'))
        self.labels[q].grid(column=0, row=+r)

仅供参考,它使用循环来遍历信息。下一部分(我遇到的问题)是计算每个员工完成的总小时数,但我的循环很糟糕,我正处于被大脑阻塞的地步。

    for u in secondNameList:
        totalHoursPerPerson = 0
        totalMinutesPerPerson = 0    
        for item in nameList:
            if item == u:
                timeParts = [int(s) for s in tdelta.split(':')]
                totalMinutesPerPerson += timeParts[1]
                totalHoursPerPerson += timeParts[0] 
                totalHoursPerPerson += totalMinutes // 60
                minutesToTake = totalMinutes // 60
                minutesToSub = minutesToTake * 60
                totalMinutesPerPerson = totalMinutes - minutesToSub
                print(totalHoursPerPerson)
                totalsPerPerson.append(f'{item} did a total of {totalHoursPerPerson} Hours')
                print(f'{item} did a total of {totalHoursPerPerson} Hours')

    totalsPerPerson = list(set(totalsPerPerson))
    print(totalsPerPerson)

输出如下图:

4
['Chris', 'Chris', 'Rory', 'John']
['Chris', 'Chris', 'Rory', 'John']
(('Chris', 'Gracey', '07:00', '16:30'), ('Chris', 'Gracey', '07:00', '16:30'), ('Rory', 'Gracey', '07:00', '16:30'), ('John', 'Smith', '07:00', '16:30'))
9
Chris did a total of 9 Hours
18
Chris did a total of 18 Hours
9
Chris did a total of 9 Hours
18
Chris did a total of 18 Hours
9
Rory did a total of 9 Hours
9
John did a total of 9 Hours
['John did a total of 9 Hours', 'Chris did a total of 18 Hours', 'Rory did a total of 9 Hours', 'Chris did a total of 9 Hours']

我真的不确定为什么它会显示 Chris 两次。我也尝试删除重复项,但它只会破坏它。

如果有更好的方法可以做到这一点,我会全力以赴。

谢谢

标签: pythonsqlloopstkinter

解决方案


好的,所以我改为更改 sql 语句。

这是我使用的语句:

SELECT FirstName, LastName, SEC_TO_TIME(SUM(TIME_TO_SEC(FinishTime) - TIME_TO_SEC(StartTime))) AS timediff FROM Sheets WHERE DateTesting >= '2018/5/7' AND DateTesting <= '2018/5/18' GROUP BY FirstName, LastName;

当然在 python 中设置变量。


推荐阅读