使用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:
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.
Duration Calculation:
- Subtracting two datetime objects gives a
timedeltaobject. Converting this to total seconds makes it simple to split into hours and minutes. minutes:02densures minutes are always displayed with two digits (e.g.,0:30instead of0:30works, but this would turn 5 minutes into0:05for consistency).
- Subtracting two datetime objects gives a
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)
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.
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
相关产品推荐
相关产品推荐

