Hi!

One of my goals for this year was to improve my coding skills. Because of that, I decided to measure the time used for coding. Introducing TaskTimer.

I didn’t find a good free tool to do so and decided to make my own little script for the purpose. (Psst, I have found a good tool for following your coding time. Check out WakaTime if you want to follow your time spent coding with your specific IDE.)

This is only a text-based script, so no fancy visuals. It appends the time used for a task to a .txt file.

You can check the code for TaskTimer below.

(Editor note: The code below is the original one. If you are interested in the new version with objects check it out from below. )

import time


DictFileName = "TaskTimerDict.txt"

def read_file_to_dict(DictFileName):
    taskDict = {}
    with open(DictFileName) as f:
        for line in f:
            (key, val) = line.split()
            taskDict[key] = int(val)
    return taskDict


def write_dict_to_file(DictFileName, dictionary):
    # This should be writing not appending as we don't want duplicate data
    with open(DictFileName, "w+") as f:
        for key in dictionary:
            f.write("{:s} {:d} \n".format(key, dictionary[key]))

def write_to_file(taskName, hours, minutes, seconds):

    fileName = "taskTimer.txt"

    with open(fileName, "a+") as f:
        f.write("Task '{:s}'. Elapsed time: {:d} h {:d} min {:d} s\n".format(taskName, hours, minutes, seconds))



def main():
    taskDict = read_file_to_dict(DictFileName)
    minutes = 0
    seconds = 0
    hours = 0

    print('Start timer by giving task name:')
    taskName = input()
    try:
        while True:
            seconds += 1

            if seconds == 60:
                minutes += 1
                seconds = 0
                print("{:s} has been running for {:d} h {:d} min {:d} s.".format(taskName, hours, minutes, seconds))
            
            if minutes == 60:
                hours += 1
                minutes = 0

            time.sleep(1)

    except KeyboardInterrupt:
        print("{:s} took: {:d} min {:d} s.".format(taskName, minutes, seconds))
        if taskName not in taskDict.keys():
            taskDict[taskName] = hours*3600 + minutes*60 + seconds
        else:
            taskDict[taskName] += hours*3600 + minutes*60 + seconds

        write_to_file(taskName, hours, minutes, seconds)
        write_dict_to_file(DictFileName, taskDict)


main()
TaskTimer running on Pycharm
TaskTimer run on PyCharm, with txt file showing.


import time

class Task:
    def __init__(self, task_name, duration):
        self.task_name = task_name
        # Duration means total time in seconds
        self.duration = duration
        self.seconds = duration % 60
        self.minutes = (duration // 60) % 60
        self.hours = duration // 3600

    def __repr__(self):
        if self.task_name == "Total":
            return "Total time: {:d} h {:d} min {:d} s\n".format(self.hours, self.minutes, self.seconds)
        return ("Task '{:s}'. Elapsed time: {:d} h {:d} min {:d} s".format(self.task_name, self.hours, self.minutes, self.seconds))


    def __add__(self, other):
        if self.task_name == "Total":
            addedTaskName = "Total"
        elif self.task_name == other.task_name:
            addedTaskName = self.task_name
        else:
            addedTaskName = self.task_name + " + "  + other.task_name
        return Task(addedTaskName, self.duration + other.duration)


def read_file_to_object_list(dict_file_name):
    taskListAll = []
    with open(dict_file_name) as f:
        for line in f:
            (name, duration) = line.split()
            taskListAll.append(Task(name, int(duration)))
    return taskListAll


def write_obj_list_to_file(dict_file_name, obj_list):
    # This should be writing not appending as we don't want duplicate data
    with open(dict_file_name, "w+") as f:
        for obj in obj_list:
            f.write("{:s} {:d} \n".format(obj.task_name, obj.duration))


def write_todays_tasks_to_file(text_file, todays_tasks):
    with open(text_file, "a+") as f:
        for task in todays_tasks:
            print(task, file=f)

        # I'm not sure how to use the total time beacuse its not clear when the day ends

        #print(total_time(todays_tasks), file=f)


def total_time(task_list):
    total = Task("Total", 0)
    for task in task_list:
        total += task
    return total


def print_all_tasks(task_list):
    """
    Function which prints all of the tasks and their times in order from largest to smallest. 
    """
    print("")

    for task in sorted(task_list, key=lambda task: task.duration, reverse=True):
        print(task)
    print(total_time(task_list))


def add_obj_to_obj_list(obj_list, obj_to_check):
    """
    This function adds objects to list if they aren't already on it. If they are, then the value of the object is updated to the sum of the object on the list and the object we were checking. 
    """

    switch = False
    for obj in obj_list:
    #Checking all the objects for same name as obj_to_check

        if obj_to_check.task_name == obj.task_name:
        # if name is same then we add the objects with same name together
            newTaskObj = obj + obj_to_check
            obj_list.remove(obj)
            # remove the original object from the list as it's outdated
            obj_list.append(newTaskObj)
            switch = True
            break
            # we don't need to check for more objects

    if not switch:
        # if the object wasn't found in the list then we add it
        obj_list.append(obj_to_check)


def main():
    

    taskObjList = read_file_to_object_list(DICT_FILE)
    todays_tasks = []

    print('Start timer by giving task name:')
    taskName = input()
    duration = 0
    try:
        while True:
            duration += 1

            if duration % 60 == 0:
                print("{:s} has been running for {:d} min.".format(taskName, duration // 60))

            time.sleep(1)
            
    except KeyboardInterrupt:
        todays_tasks.append(Task(taskName, duration))
        for task in todays_tasks:
            print(task)
            add_obj_to_obj_list(taskObjList ,task)
        
        write_todays_tasks_to_file(TEXT_FILE, todays_tasks)
        write_obj_list_to_file(DICT_FILE, taskObjList)


if __name__ == "__main__":
    # Names of files
    DICT_FILE = "TaskTimerDict.txt"
    TEXT_FILE = "TaskTimer.txt"
    main()
    #print_all_tasks(read_file_to_object_list(DICT_FILE))

I’m going to start the #100DaysOfCode challenge and this could be considered as part “zero”.

You can follow the challenge on Twitter.


This was only a quick update and I tried using the normal Gutenberg editor instead of Elementor. The next one is a big guide about creating your own website so stay tuned for that!

Similar Posts

2 Comments

  1. Hi there! I could have sworn I’ve visited this blog before but after
    going through a few of the articles I realized
    it’s new to me. Anyhow, I’m certainly pleased I
    found it and I’ll be book-marking it and checking back regularly!

Leave a Reply