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.
Python code
37 linesimport 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
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
- Use `pandas.read_csv` to load and aggregate hours with groupby for more complex reporting.
- 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
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
- Build a Secure Local Password Vault with Encrypted Storage in Python medium
Keep learning
Related tutorials and quizzes for this topic.