You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python读取Watson生成的JSON工时文件并生成自定义报表

Solution to Generate Timesheet Report

Here's a complete Python script that transforms your Watson JSON data into the exact report format you want, including calculating the total time spent:

#! /opt/homebrew/bin/python3
import json
from datetime import datetime

# Load the JSON data from file
with open("timesheet.json", "r", encoding="utf-8") as f:
    data = json.load(f)

total_seconds = 0  # Track total time spent across all entries

# Process each entry in the timesheet
for entry in data:
    # Convert ISO 8601 time strings to datetime objects
    start_dt = datetime.fromisoformat(entry["start"])
    stop_dt = datetime.fromisoformat(entry["stop"])
    
    # Calculate duration between start and stop
    duration = stop_dt - start_dt
    duration_seconds = duration.total_seconds()
    total_seconds += duration_seconds
    
    # Format duration as HH:MM (ensuring two digits for minutes)
    hours = int(duration_seconds // 3600)
    minutes = int((duration_seconds % 3600) // 60)
    duration_str = f"{hours}:{minutes:02d}"
    
    # Format date and time components to match your desired output
    date_part = start_dt.strftime("%a %m-%d-%Y")  # e.g., "Fri 10-01-2021"
    start_time = start_dt.strftime("%H:%M")       # e.g., "09:30"
    stop_time = stop_dt.strftime("%H:%M")         # e.g., "11:30"
    
    # Convert tags list to a comma-separated string (skip if empty)
    tags_str = ", ".join(entry["tags"]) if entry["tags"] else ""
    
    # Build the final line for this entry
    line_components = [
        date_part,
        f"{start_time} - {stop_time}",
        f"= {duration_str}",
        entry["project"]
    ]
    if tags_str:
        line_components.append(tags_str)
    
    # Print the formatted line
    print(" ".join(line_components))

# Calculate and print the total time spent
total_hours = int(total_seconds // 3600)
total_minutes = int((total_seconds % 3600) // 60)
print(f"\nTotal = {total_hours}:{total_minutes:02d}")

Key Parts Explained for Beginners:

  1. Datetime Parsing:

    • datetime.fromisoformat() takes the Watson time strings (like "2021-10-01T09:30:00+02:00") and turns them into datetime objects, which let us easily calculate time differences and format dates.
  2. Duration Calculation:

    • Subtracting two datetime objects gives a timedelta object. Converting this to total seconds makes it simple to split into hours and minutes.
    • minutes:02d ensures minutes are always displayed with two digits (e.g., 0:30 instead of 0:30 works, but this would turn 5 minutes into 0:05 for consistency).
  3. Date/Time Formatting:

    • strftime() lets us customize how dates/times look:
      • %a: Short weekday name (Fri, Mon)
      • %m-%d-%Y: Month-day-year format (10-01-2021)
      • %H:%M: 24-hour time with minutes (09:30)
  4. Tag Handling:

    • ", ".join(entry["tags"]) converts the list of tags into a readable string. If there are no tags, we skip adding this part to avoid extra spaces in the output.
  5. Total Time:

    • We accumulate all duration seconds as we process each entry, then convert the total back to hours and minutes for the final summary line.

When you run this script, it will output exactly the report format you provided, including the total time at the end.

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:09:07