Of course! Here is a Python script that uses the powerful moviepy library to cut a video into multiple clips based on a list of start and end timestamps.
Key Features of this Script:
- Easy to Use: You only need to edit the configuration section at the top of the script.
- Flexible Timestamps: You can provide timestamps as strings in
HH:MM:SS format (e.g., "00:01:23") or as seconds (e.g., 83).
- Automatic Directory Creation: The script creates an output folder for your clips if it doesn't already exist.
- Clear Progress: It prints messages to the console so you know what it's doing.
- Keeps Audio: The audio from the original video is included in the cut clips.
Step 1: Install a Prerequisite (ffmpeg)
The moviepy library uses another program called ffmpeg behind the scenes to do the heavy lifting of video processing. You need to install it first.
- Windows: Download
ffmpeg from their official site. Unzip it, and add the bin folder to your system's PATH. (A simpler way is to use a package manager like Chocolatey: choco install ffmpeg).
- macOS: Use Homebrew:
brew install ffmpeg
- Linux (Debian/Ubuntu):
sudo apt update && sudo apt install ffmpeg
Step 2: Install the Python Library
Now, install the moviepy library using pip:
pip install moviepy
Step 3: The Python Script
Save the following code as a Python file (e.g., video_cutter.py).
import os
from moviepy.editor import VideoFileClip
def cut_video_into_clips(source_path, clips_data, output_dir, output_prefix="clip"):
"""
Cuts a video into multiple clips based on a list of timestamps.
Args:
source_path (str): The path to the source video file.
clips_data (list): A list of tuples, where each tuple contains the
start and end time of a clip.
Times can be in seconds (e.g., 60) or as a
string "HH:MM:SS" (e.g., "00:01:00").
output_dir (str): The directory where the output clips will be saved.
output_prefix (str): A prefix for the output filenames.
"""
# Create the output directory if it doesn't exist
if not os.path.exists(output_dir):
print(f"Creating output directory: {output_dir}")
os.makedirs(output_dir)
# Check if the source video file exists
if not os.path.isfile(source_path):
print(f"Error: Source video not found at '{source_path}'")
return
# Load the main video clip
# Using 'with' ensures the file is closed automatically
try:
with VideoFileClip(source_path) as video:
print(f"Successfully loaded video: {source_path}")
print(f"Video duration: {video.duration:.2f} seconds")
# Iterate through the timestamps and create clips
for i, (start_time, end_time) in enumerate(clips_data):
clip_num = i + 1
# Generate the output filename
# e.g., 'output_clips/clip_1.mp4'
_, file_extension = os.path.splitext(source_path)
output_filename = f"{output_prefix}_{clip_num}{file_extension}"
output_path = os.path.join(output_dir, output_filename)
print(f"\nProcessing Clip #{clip_num}...")
print(f" Start: {start_time}")
print(f" End: {end_time}")
print(f" Output: {output_path}")
try:
# Create the subclip
subclip = video.subclip(start_time, end_time)
# Write the subclip to a file
# codec="libx264" and audio_codec="aac" are common and compatible choices
subclip.write_videofile(output_path, codec="libx264", audio_codec="aac")
# Close the subclip to free up memory
subclip.close()
except Exception as e:
print(f" An error occurred while creating clip #{clip_num}: {e}")
except Exception as e:
print(f"An error occurred while loading the main video: {e}")
print("\nAll clips have been processed. Check the 'output_clips' folder.")
# ==============================================================================
# --- CONFIGURATION ---
# ==============================================================================
if __name__ == "__main__":
# 1. Set the path to your source video file
source_video_path = "my_long_video.mp4"
# 2. Define the timestamps for the clips you want to create.
# Format: [ (start_time_1, end_time_1), (start_time_2, end_time_2), ... ]
# You can use seconds (e.g., 10.5) or "HH:MM:SS.ms" strings (e.g., "00:00:10.500").
clips_to_create = [
("00:00:15", "00:00:28"), # Clip 1: from 15s to 28s
("00:01:10", "00:01:45"), # Clip 2: from 1m 10s to 1m 45s
(150, 162.5), # Clip 3: from 150s (2m 30s) to 162.5s
("00:03:05.200", "00:03:12"), # Clip 4: including milliseconds
]
# 3. Set the name of the folder where you want to save the clips
output_folder = "output_clips"
# 4. (Optional) Set a prefix for the names of your output files
output_file_prefix = "highlight" # will result in "highlight_1.mp4", "highlight_2.mp4", etc.
# --- Run the function with your configuration ---
cut_video_into_clips(source_video_path, clips_to_create, output_folder, output_file_prefix)
How to Use the Script
- Place the Script and Video: Put the
video_cutter.py script in the same folder as your source video file (e.g., my_long_video.mp4).
- Configure the Script: Open
video_cutter.py with a text editor and modify the CONFIGURATION section:
- Change
source_video_path to the exact filename of your video.
- Update the
clips_to_create list with the start and end times for each clip you want.
- You can also change the
output_folder and output_file_prefix if you wish.
- Run from Terminal: Open a terminal or command prompt, navigate to the folder containing your script and video, and run the script:
python video_cutter.py
The script will start processing, and a new folder (e.g., output_clips) will be created in the same directory, containing your new, shorter video files named highlight_1.mp4, highlight_2.mp4, and so on.