Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Build a Personal Work Hours Tracker in Python

A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.

Medium Python 3.9+ Jun 28, 2026 Files & data 2 views 0 copies

Python code

37 lines
Python 3.9+
import csv
from pathlib import Path
from datetime import datetime, date

class WorkHoursTracker:
    def __init__(self, file_path="work_hours.csv"):
        self.file_path = Path(file_path)
        if not self.file_path.exists():
            with open(self.file_path, "w", newline="") as f:
                writer = csv.writer(f)
                writer.writerow(["date", "start_time", "end_time", "hours_worked"])

    def log_hours(self, start, end):
        start_dt = datetime.strptime(start, "%H:%M")
        end_dt = datetime.strptime(end, "%H:%M")
        hours = (end_dt - start_dt).total_seconds() / 3600
        with open(self.file_path, "a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([date.today().isoformat(), start, end, round(hours, 2)])

    def weekly_summary(self):
        today = date.today()
        week_start = today.isocalendar()
        total = 0.0
        with open(self.file_path, "r") as f:
            reader = csv.DictReader(f)
            for row in reader:
                row_date = datetime.strptime(row["date"], "%Y-%m-%d").date()
                if row_date.isocalendar()[1] == week_start[1] and row_date.year == today.year:
                    total += float(row["hours_worked"])
        print(f"Week {week_start[1]} total hours: {total:.2f}")

if __name__ == "__main__":
    tracker = WorkHoursTracker()
    tracker.log_hours("09:00", "12:30")
    tracker.log_hours("13:30", "17:00")
    tracker.weekly_summary()

Output

stdout
Week 17 total hours: 7.00

How it works

The WorkHoursTracker class uses the standard library csv and datetime modules to persist work logs. The log_hours() method accepts start and end times as strings, parses them with strptime, computes the difference in hours, and appends a row to a CSV file. The weekly_summary() method reads all records, filters for the current ISO week, sums the hours, and prints the total. The CSV is automatically created with a header row on first use, and file paths are handled portably with pathlib.Path.

Common mistakes

  • Forgetting to handle overnight shifts where end time is before start time (the code assumes same-day work only).
  • Not rounding hours before writing, leading to floating-point precision artifacts in the CSV.
  • Assuming the CSV file already exists – the initializer checks and creates a header if absent.

Variations

  1. Use `pandas.read_csv` to load and aggregate hours with groupby for more complex reporting.
  2. Store logs in a SQLite database instead of CSV for better querying and concurrency.

Real-world use cases

  • Freelancers tracking billable hours across multiple clients and exporting weekly reports.
  • Small teams logging shift times to payroll without a dedicated HR system.
  • Personal productivity monitoring to analyze time spent on different projects over a week.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.