Are there any efficient algorithms or packages for time stats in Python?

Viewed 41

I have been trying to implement a user statistics function to my Discord server using sqlite and python. The user stats will display like this: hours:minutes:seconds.

I have set so the daily statistics will reset the user's local time 5AM. Using the code below, it takes some time and I don't think this is an efficient way.

Are there any packages or efficient algorithms for these types of tasks?

class hours(datetime.timedelta):
    def __str__(self):
        seconds = self.total_seconds()
        hours = seconds // 3600
        minutes = (seconds % 3600) // 60
        seconds = seconds % 60
        str = f'{int(hours)}:{int(minutes):02d}:{int(seconds):02d}'
        return (str)

def saveStats(user, startTime, endTime):
    find = logs.col_values(1)
    rownum = find.index(str(user)) + 1
    logs.delete_row(rownum)
    conn = sqlite3.connect ('data.db')
    c = conn.cursor()

    startMonth = str(startTime.year) + str(startTime.month)
    endMonth = str(endTime.year) + str(endTime.month)

    if (startTime.date() != endTime.date()):
        save_day0 = (datetime.datetime.combine(endTime.date(), datetime.time(0, 0))) - startTime
        save_day1 = endTime - (datetime.datetime.combine(endTime.date(), datetime.time(0, 0)))
    elif(startTime.date() == endTime.date()):
        save_day0 = endTime - startTime
        save_day1 = datetime.timedelta(hours=0, minutes=0, seconds=0)

    #monthly
    if (startMonth != endMonth):
        save_month0 = (datetime.datetime.combine(endTime.date(), datetime.time(0, 0))) - startTime
        save_month1 = endTime - (datetime.datetime.combine(endTime.date(), datetime.time(0, 0)))
    elif(startMonth == endMonth):
        save_month0 = (endTime - startTime)
        save_month1 = datetime.timedelta(hours=0, minutes=0, seconds=0)
    

    if c.execute('SELECT * FROM daily WHERE id =?',(f"{str(user)}{str(startTime.date())}",)).fetchone() == None:
        c.execute("INSERT INTO daily(id, user, date, study_time) VALUES(?,?,?,?)"\
            ,(f"{str(user)}{str(startTime.date())}",str(user),str(startTime.date()),str(save_day0)))
    else:
        original_study_time = datetime.datetime.strptime(c.execute('SELECT * FROM daily WHERE id =?',(f"{str(user)}{str(endTime.date())}",)).fetchone()[3], "%H:%M:%S") 
        save_day2 = (save_day0 + original_study_time).strftime("%H:%M:%S")
        c.execute("UPDATE daily SET user = ?, date = ?, study_time = ? WHERE id = ?",(str(user), str(startTime.date()), str(save_day2), f"{str(user)}{str(startTime.date())}"))
    
    if save_day1 != datetime.timedelta(hours=0, minutes=0, seconds=0):
        c.execute("INSERT INTO daily(id, user, date, study_time) VALUES(?,?,?,?)"\
            ,(f"{str(user)}{str(endTime.date())}",str(user),str(endTime.date()),str(save_day1)))
    
    #monthly
    if c.execute('SELECT * FROM month WHERE id =?',(f"{str(user)}{startMonth}",)).fetchone() == None:
        c.execute("INSERT INTO month(id, user, month, study_time) VALUES(?,?,?,?)"\
            ,(f"{str(user)}{startMonth}",str(user),str(startMonth),str(save_month0)))
    else:
        original_study_time = datetime.datetime.strptime(AddDay(c.execute('SELECT * FROM month WHERE id =?',(f"{str(user)}{startMonth}",)).fetchone()[3]), "%d:%H:%M:%S") - datetime.datetime(1900, 1, 1)
        save_month2 = (save_month0 + original_study_time).total_seconds()
        h = save_month2 // 3600
        m = (save_month2 % 3600) // 60
        s = save_month2 % 60
        save_month2 = f'{int(h)}:{int(m):02d}:{int(s):02d}'
        c.execute("UPDATE month SET user = ?, month = ?, study_time = ? WHERE id = ?",(str(user), str(startMonth), save_month2, f"{str(user)}{startMonth}"))
    
    if save_month1 != datetime.timedelta(hours=0, minutes=0, seconds=0):
        c.execute("INSERT INTO month(id, user, month, study_time) VALUES(?,?,?,?)"\
            ,(f"{str(user)}{endMonth}",str(user),endMonth,str(save_month1)))

    #all-time
    save_all = save_day0 + save_day1

    if c.execute('SELECT * FROM alltime WHERE id =?',(f"{str(user)}",)).fetchone() == None:
        c.execute("INSERT INTO alltime(id, user, study_time) VALUES(?,?,?)"\
            ,(f"{str(user)}",str(user),str(save_all)))
    else:
        original_study_time = datetime.datetime.strptime(AddDay(c.execute('SELECT * FROM alltime WHERE id =?',(f"{str(user)}",)).fetchone()[2]), "%d:%H:%M:%S") - datetime.datetime(1900, 1, 1)
        save_all = (save_all + original_study_time).total_seconds()
        h = save_all // 3600
        m = (save_all % 3600) // 60
        s = save_all % 60
        save_all = f'{int(h)}:{int(m):02d}:{int(s):02d}'
        c.execute("UPDATE alltime SET user = ?, study_time = ? WHERE id = ?",(str(user), save_month2, f"{str(user)}"))
    
    conn.commit()
    conn.close()

The table's columns

                                        id text PRIMARY KEY,
                                        user text NOT NULL,
                                        date text,
                                        study_time text
                                    ); """

    sql_create_monthly_table = """ CREATE TABLE IF NOT EXISTS month (
                                        id text PRIMARY KEY,
                                        user text NOT NULL,
                                        month text,
                                        study_time text
                                    ); """
    
    sql_create_alltime_table = """ CREATE TABLE IF NOT EXISTS alltime (
                                        id text PRIMARY KEY,
                                        user text NOT NULL,
                                        study_time text
                                    ); """
1 Answers
Related