Last active
January 28, 2025 20:28
-
-
Save 0xack13/6923c09d17838f83279cea5a7114ce9c to your computer and use it in GitHub Desktop.
compare_ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from datetime import datetime | |
def prepend_diff(input_file, output_file): | |
# Read all lines from the input file | |
with open(input_file, 'r') as file: | |
lines = file.readlines() | |
output_lines = [] | |
prev_timestamp = None | |
for line in lines: | |
try: | |
# Extract the timestamp (assuming it's the first part of the line) | |
timestamp_str = line.split()[0] # Extract the timestamp portion | |
# Trim the fractional seconds to 6 digits (microseconds) | |
if "." in timestamp_str: | |
timestamp_str = timestamp_str[:26] + "Z" # Keep up to microseconds and add "Z" | |
# Parse the timestamp in the format: '2025-01-16T04:37:19.234061Z' | |
current_timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S.%fZ') | |
except (ValueError, IndexError): | |
# If no valid timestamp is found, add the line as-is and skip | |
output_lines.append(line) | |
continue | |
if prev_timestamp is not None: | |
# Calculate the difference in seconds | |
diff = int((current_timestamp - prev_timestamp).total_seconds()) | |
# Prepend the difference to the current line | |
output_lines.append(f"{diff} seconds {line}") | |
else: | |
output_lines.append(line) | |
prev_timestamp = current_timestamp | |
# Write the output to the output file | |
with open(output_file, 'w') as file: | |
file.writelines(output_lines) | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print("Usage: python prepend_diff.py <input_file> [output_file]") | |
sys.exit(1) | |
input_file = sys.argv[1] | |
output_file = sys.argv[2] if len(sys.argv) > 2 else 'output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment