使用Python提取写入TXT文件:按时间间隔拆分会话数据
Python Solution to Split Time Interval Data into Sessions
Got it, let's break down how to solve this with Python. I'll walk you through a complete implementation that reads your timestamp-based TXT file, detects session breakpoints (based on a time threshold you define), and writes each session's start/end time to a new condensed TXT file.
Core Approach
Here's the high-level logic we'll use:
- Read and parse the raw timestamp data from your input file, skipping any empty lines.
- Calculate time gaps between consecutive timestamps. If a gap exceeds your defined threshold, we'll split the data into a new session.
- Track sessions by keeping track of the start and end time for each continuous block of timestamps.
- Write results to an output file, with each session represented as a single line of start-end time.
Complete Code Implementation
from datetime import datetime def split_time_into_sessions(input_file_path, output_file_path, breakpoint_threshold_minutes=30): # Read all valid timestamps from the input file with open(input_file_path, 'r') as input_file: # Skip empty lines and strip whitespace from each timestamp raw_timestamps = [line.strip() for line in input_file if line.strip()] if not raw_timestamps: print("Warning: No valid timestamp data found in the input file.") return # Define your timestamp format here (match what's in your TXT file) # Example formats: "%Y-%m-%d %H:%M:%S", "%m/%d/%Y %I:%M %p", "%H:%M:%S" timestamp_format = "%Y-%m-%d %H:%M:%S" sessions = [] # Initialize the first session with the first timestamp current_session_start = datetime.strptime(raw_timestamps[0], timestamp_format) current_session_end = current_session_start # Iterate through remaining timestamps to detect breakpoints for ts_str in raw_timestamps[1:]: try: current_timestamp = datetime.strptime(ts_str, timestamp_format) except ValueError: print(f"Skipping invalid timestamp: {ts_str} (doesn't match format {timestamp_format})") continue # Calculate the time gap between current and previous timestamp (in minutes) time_gap_minutes = (current_timestamp - current_session_end).total_seconds() / 60 if time_gap_minutes > breakpoint_threshold_minutes: # Gap exceeds threshold: finalize current session and start a new one sessions.append((current_session_start, current_session_end)) current_session_start = current_timestamp # Update the end time of the current session current_session_end = current_timestamp # Add the last session to our list sessions.append((current_session_start, current_session_end)) # Write the condensed session data to the output file with open(output_file_path, 'w') as output_file: for start, end in sessions: output_line = f"{start.strftime(timestamp_format)} - {end.strftime(timestamp_format)}" output_file.write(output_line + "\n") print(f"Success! Split data into {len(sessions)} sessions. Results saved to {output_file_path}") # ------------------------------ # Example usage (customize these values!) # ------------------------------ split_time_into_sessions( input_file_path="raw_time_data.txt", output_file_path="session_summary.txt", breakpoint_threshold_minutes=30 # Adjust this to your definition of a "breakpoint" )
Customization Tips
- Adjust the timestamp format: Modify
timestamp_formatto match the format in your input file. For example, if your timestamps look like05/01/2024 09:00 AM, use"%m/%d/%Y %I:%M %p". - Tweak the breakpoint threshold: Change
breakpoint_threshold_minutesto set how big a gap needs to be to split sessions. If you consider a 1-hour gap a breakpoint, set it to60. - Handle raw interval data: If your input file has time intervals (instead of full timestamps), you can skip the datetime parsing and directly compare each interval to your threshold. Let me know if you need help adapting the code for that case!
Example Input/Output
Input File (raw_time_data.txt)
2024-05-01 09:00:00 2024-05-01 09:15:00 2024-05-01 09:30:00 2024-05-01 11:00:00 # 90-minute gap here (exceeds 30min threshold) 2024-05-01 11:10:00 2024-05-01 11:25:00
Output File (session_summary.txt)
2024-05-01 09:00:00 - 2024-05-01 09:30:00 2024-05-01 11:00:00 - 2024-05-01 11:25:00
内容的提问来源于stack exchange,提问作者Vincent
相关产品推荐
相关产品推荐

