Here's a Python script that uses moviepy to cut a video into clips based on timestamps:
python
import os
from moviepy.editor import VideoFileClip
from datetime import datetime
def parse_timestamp(timestamp):
"""
Parse timestamp string to seconds.
Accepts formats: 'HH:MM:SS', 'MM:SS', or seconds as float/int
"""
if isinstance(timestamp, (int, float)):
return float(timestamp)
parts = timestamp.split(':')
if len(parts) == 3: # HH:MM:SS
hours, minutes, seconds = map(float, parts)
return hours * 3600 + minutes * 60 + seconds
elif len(parts) == 2: # MM:SS
minutes, seconds = map(float, parts)
return minutes * 60 + seconds
else:
return float(timestamp)
def cut_video_clips(input_video, timestamps, output_dir="clips"):
"""
Cut video into clips based on timestamp pairs.
Args:
input_video: Path to input video file
timestamps: List of tuples (start_time, end_time) or list of dictionaries
with 'start', 'end', and optionally 'name' keys
output_dir: Directory to save clips (default: "clips")
"""
# Create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Load the video
video = VideoFileClip(input_video)
video_name = os.path.splitext(os.path.basename(input_video))[0]
# Process each timestamp pair
for i, timestamp_pair in enumerate(timestamps):
# Handle different input formats
if isinstance(timestamp_pair, dict):
start_time = parse_timestamp(timestamp_pair['start'])
end_time = parse_timestamp(timestamp_pair['end'])
clip_name = timestamp_pair.get('name', f"{video_name}_clip_{i+1}")
else:
start_time = parse_timestamp(timestamp_pair[0])
end_time = parse_timestamp(timestamp_pair[1])
clip_name = f"{video_name}_clip_{i+1}"
# Extract the clip
clip = video.subclip(start_time, end_time)
# Save the clip
output_path = os.path.join(output_dir, f"{clip_name}.mp4")
print(f"Creating clip {i+1}: {start_time}s to {end_time}s -> {output_path}")
# Write the clip with the same codec as the original
clip.write_videofile(output_path, codec='libx264', audio_codec='aac')
clip.close()
video.close()
print(f"\nAll clips saved to {output_dir}/")
# Example usage
if __name__ == "__main__":
# Example 1: Using tuples of timestamps
timestamps_tuples = [
("0:00", "0:30"), # First 30 seconds
("1:00", "1:45"), # 1 minute to 1:45
("2:30", "3:00"), # 2:30 to 3:00
(180, 210), # Using seconds: 3:00 to 3:30
]
# Example 2: Using dictionaries with custom names
timestamps_dicts = [
{"start": "0:00", "end": "0:30", "name": "intro"},
{"start": "1:00", "end": "1:45", "name": "main_scene"},
{"start": "2:30", "end": "3:00", "name": "conclusion"},
]
# Run the script
input_video = "your_video.mp4" # Replace with your video file
# Choose one of the timestamp formats
cut_video_clips(input_video, timestamps_tuples)
# or
# cut_video_clips(input_video, timestamps_dicts, output_dir="my_clips")
To use this script:
First install the required library:
bash
pip install moviepy
Modify the script with your video file path and timestamps:
You can also create a more advanced version that reads timestamps from a file:
python
def read_timestamps_from_file(filename):
"""
Read timestamps from a text file.
Expected format: start_time end_time [optional_name]
"""
timestamps = []
with open(filename, 'r') as f:
for line in f:
parts = line.strip().split()
if len(parts) >= 2:
if len(parts) >= 3:
# Has custom name
timestamps.append({
'start': parts[0],
'end': parts[1],
'name': '_'.join(parts[2:])
})
else:
# Just start and end times
timestamps.append((parts[0], parts[1]))
return timestamps
# Usage
timestamps = read_timestamps_from_file("timestamps.txt")
cut_video_clips("video.mp4", timestamps)