Maintenance

Site is under maintenance — quizzes are still available.

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

Generate Timesheet Reports from Daily Logs in Python

Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.

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

Python code

51 lines
Python 3.9+
import json
from pathlib import Path
from collections import defaultdict

def generate_timesheet_report(daily_logs: list[dict]) -> str:
    """
    Generate a timesheet report from daily log entries.
    
    Args:
        daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
    
    Returns:
        Formatted timesheet report string
    """
    # Aggregate hours by project
    project_hours = defaultdict(float)
    project_details = defaultdict(list)
    
    for entry in daily_logs:
        project = entry['project']
        project_hours[project] += entry['hours']
        project_details[project].append(entry)
    
    # Build report
    lines = ["Timesheet Report", "=" * 40, ""]
    total_hours = 0.0
    
    for project in sorted(project_hours.keys()):
        lines.append(f"Project: {project}")
        lines.append(f"Total Hours: {project_hours[project]:.1f}")
        lines.append("Details:")
        for entry in project_details[project]:
            lines.append(f"  {entry['date']} - {entry['task']} ({entry['hours']}h)")
        lines.append("")
        total_hours += project_hours[project]
    
    lines.append("=" * 40)
    lines.append(f"Grand Total: {total_hours:.1f} hours")
    
    return "\n".join(lines)

if __name__ == "__main__":
    sample_logs = [
        {"date": "2024-01-15", "project": "Alpha", "hours": 4.0, "task": "Feature X"},
        {"date": "2024-01-15", "project": "Beta", "hours": 3.5, "task": "Bug fix"},
        {"date": "2024-01-16", "project": "Alpha", "hours": 5.0, "task": "Deploy"},
        {"date": "2024-01-16", "project": "Gamma", "hours": 2.0, "task": "Review"}
    ]
    
    report = generate_timesheet_report(sample_logs)
    print(report)

Output

stdout
Timesheet Report
========================================

Project: Alpha
Total Hours: 9.0
Details:
  2024-01-15 - Feature X (4.0h)
  2024-01-16 - Deploy (5.0h)

Project: Beta
Total Hours: 3.5
Details:
  2024-01-15 - Bug fix (3.5h)

Project: Gamma
Total Hours: 2.0
Details:
  2024-01-16 - Review (2.0h)

========================================
Grand Total: 14.5 hours

How it works

The generate_timesheet_report function uses defaultdict(list) to group log entries by project while accumulating total hours per project via defaultdict(float). Sorting the projects alphabetically ensures a consistent, predictable report order. Each entry's date, task, and hours are preserved to provide a detailed breakdown. Finally, a grand total is computed by summing all project subtotals, and the entire report is joined into a single string with newline separators.

Common mistakes

  • Forgetting to convert hours from strings to floats before summing them.
  • Assuming all entries have the same keys, leading to KeyError when a field is missing.
  • Using a regular dict instead of `defaultdict`, which requires manually checking and initializing keys.
  • Not handling empty input gracefully, which would produce a report with no projects.

Variations

  1. Use `pandas` to group and summarize log data for larger datasets and advanced analytics.
  2. Export the report as a CSV file with `csv.writer` for integration with spreadsheet tools.

Real-world use cases

  • Freelancers automatically consolidate their daily task logs into a weekly client invoice summary.
  • Small teams parse a shared JSON feed of time entries and email the resulting report to project managers.
  • Contractors convert a plain-text daily journal into a structured timesheet for payroll submission.

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.