Introducing a Simple Python Script for Time Tracking

Construction manager writing time sheet on notebook
Construction manager writing time sheet on notebook / Construction Photography/Avalon/GettyImages
facebooktwitterreddit

If you are a freelance worker, independent contractor, or just someone who wants to keep better track of their time. You likely know that it can be a real challenge to find a good, easy way to track how much time you spend on each project throughout the day. However, with a simple Python script, you can keep track of as many activities as you want each day and log them to review anytime you want.

What Does the Simple Time Tracker Do?

When you run the Python time tracker script, you get a list of buttons that you can label with the names of the tasks you want to track. Clicking on the button will change its color to green to let you know the script started a timer for that task. Clicking the button again will stop the timer for that task, or you can begin timing another task by clicking another button.

  • Every time you click a button, the system updates and saves the log file.
  • There is no need to enter times or dates.
  • There is no need to save or load anything. Run the program and click the button for the task you are doing to begin tracking it.
  • The system automatically saves a new log every day, so you start fresh but still know how much time you spent on a project.
  • How much time you spent on each task today is printed on the button.

How Does the Simple Time Tracker Code Work?

The code is actually fairly simple. First, we import our libraries, including the tkinter Library, which is essential for the graphical user interface (GUI), so we can get away from the command prompt.

import tkinter as tk

from tkinter import messagebox

import time

import threading

import json

from datetime import datetime, date

Next, we’ve set up our variables to track things like our start and finish time and which task is currently active.

active_activity = None

start_time = None

daily_log = {}

cumulative_log = {}

log_file = 'daily_time_logs.json'

last_save_date = date.today()

Next, we create our functions, which include the toggle activity, which starts and stops the timer and records the elapsed time,. Other important functions include the auto-save function, which automatically saves every 30 minutes, the save_log(), load_log(), and more.

Of special importance is that you can change how frequently the program automatically saves by changing the value in “time.sleep.” There are 1,800 seconds in 30 minutes, so set the value for what is most suitable for you.

def auto_save():

while True:

time.sleep(1800) # Save every 30 minutes

save_log()

check_new_day()

Another important part of the code is the activities. You can label each button correctly by changing the text between quotations to the task you want to track. You can also add more or remove some if you need to.

activities = ["Activity 1", "Activity 2", "Activity 3", "Activity 4", "Activity 5",

"Activity 6", "Activity 7", "Activity 8", "Activity 9", "Activity 10"]

buttons = {}

load_log()

manual

Simple Time Tracker Complete Code

import tkinter as tk

from tkinter import messagebox

import time

import threading

import json

from datetime import datetime, date

# Initialize global variables

active_activity = None

start_time = None

daily_log = {}

cumulative_log = {}

log_file = 'daily_time_logs.json'

last_save_date = date.today()

# Function to start/stop tracking

def toggle_activity(activity):

global active_activity, start_time

if active_activity == activity:

# Stop tracking

end_time = time.time()

elapsed_time = end_time - start_time

daily_log[activity].append(elapsed_time)

start_time = None

active_activity = None

buttons[activity]['bg'] = 'SystemButtonFace'

else:

if active_activity is not None:

# Stop current activity

toggle_activity(active_activity)

# Start new activity

active_activity = activity

start_time = time.time()

buttons[activity]['bg'] = 'lightgreen'

update_button_labels()

save_log() # Save the log every time an activity is started or stopped

# Function to save log periodically

def auto_save():

while True:

time.sleep(1800) # Save every 30 minutes

save_log()

check_new_day()

# Function to save log to a file

def save_log():

with open(log_file, 'w') as f:

json.dump(cumulative_log, f)

print(f"Log saved at {datetime.now()}")

# Function to load log from a file

def load_log():

global cumulative_log, daily_log, last_save_date

try:

with open(log_file, 'r') as f:

cumulative_log = json.load(f)

# Check if there's a log for today

today_str = str(date.today())

if today_str in cumulative_log:

daily_log = cumulative_log[today_str]

else:

daily_log = {activity: [] for activity in activities}

except FileNotFoundError:

cumulative_log = {}

daily_log = {activity: [] for activity in activities}

# Function to check if a new day has started

def check_new_day():

global last_save_date

if date.today() != last_save_date:

archive_log()

reset_daily_log()

last_save_date = date.today()

# Function to archive the daily log into the cumulative log

def archive_log():

global cumulative_log

cumulative_log[str(last_save_date)] = daily_log

save_log()

print("Daily log archived into cumulative log")

# Function to reset the daily log for a new day

def reset_daily_log():

global daily_log

daily_log = {activity: [] for activity in activities}

update_button_labels()

print("Daily log reset for a new day")

# Function to update button labels with the time spent

def update_button_labels():

for activity in activities:

total_time = sum(daily_log[activity])

formatted_time = format_time(total_time)

buttons[activity].config(text=f"{activity}: {formatted_time}")

# Function to format time in hours and minutes

def format_time(seconds):

minutes, seconds = divmod(seconds, 60)

hours, minutes = divmod(minutes, 60)

return f"{int(hours)}h {int(minutes)}m"

# Create main application window

root = tk.Tk()

root.title("Activity Tracker")

# Define activities

activities = ["Activity 1", "Activity 2", "Activity 3", "Activity 4", "Activity 5",

"Activity 6", "Activity 7", "Activity 8", "Activity 9", "Activity 10"]

buttons = {}

# Load previous log

load_log()

# Create buttons for each activity

for activity in activities:

button = tk.Button(root, text=f"{activity}: 0h 0m", width=20, height=2, command=lambda act=activity: toggle_activity(act))

button.pack(pady=5)

buttons[activity] = button

# Update the button labels with the loaded log

update_button_labels()

# Start auto-save thread

save_thread = threading.Thread(target=auto_save, daemon=True)

save_thread.start()

# Start the application

root.mainloop()

# Save log when closing

archive_log()

save_log()

Here is the complete code for you to copy and paste. Remember to adjust the auto-save time if you need to and change the names of the buttons to reflect the tasks you are tracking.

Please consider following Geeksided on Facebook to stay up to date with our Python projects and to leave questions and comments.

feed