SoFunction
Updated on 2025-03-04

Python deletes a certain segment of a video and retains other segments of time

To use Python to delete a segment of a video and preserve other time periods, you can use the moviepy library to do so. moviepy is a very powerful video processing library that can easily perform video cutting, merging, adding special effects and other operations.

Here is a basic example of using moviepy to delete a certain segment in a video:

Install moviepy

First, make sure you have the moviepy library installed. If not installed, you can use the following command to install:

pip install moviepy

Delete a certain segment of the video

Suppose you have a video file input_video.mp4 and you want to delete the video from start_time to end_time. We will implement the deletion by dividing the video into two parts before and after and then merging them.

from  import VideoFileClip, concatenate_videoclips

# Enter the video file pathinput_video_path = 'input_video.mp4'
# Output video file pathoutput_video_path = 'output_video.mp4'

# Define the time period for deletionstart_time_to_delete = 10  # Delete the part that starts from 10 secondsend_time_to_delete = 20    # Delete the part that ends at 20 seconds
# Load video filevideo = VideoFileClip(input_video_path)

# Get the total length of the videovideo_duration = 

# Split video: Keep the two segments before and after deleting the segmentclip1 = (0, start_time_to_delete)  # Start time from the start of the video to the beginning of the deleted segmentclip2 = (end_time_to_delete, video_duration)  # From the end time of deleting segment to the end of the video
# Merge the remaining partsfinal_clip = concatenate_videoclips([clip1, clip2])

# Write output videofinal_clip.write_videofile(output_video_path, codec='libx264', audio_codec='aac')

Code description:

Import moviepy: Use VideoFileClip to load videos and use concatenate_videoclips to merge multiple video clips.

Define time period: Set the time period you want to delete. start_time_to_delete and end_time_to_delete are the start and end times to be deleted, respectively.

Split video: Use the subclip(start, end) method to extract the required clip from the video. We extracted the parts before and after the deletion period.

Merge videos: Use concatenate_videoclips to merge the front and rear parts and delete the middle part.

Export video: Use write_videofile to write the merged video to the output file.

Notes:

Video processing may take some time, depending on the size of the video and processing complexity.

write_videofile will output a new video file, supporting various video formats, but require the installation of appropriate codecs (such as libx264 and aac).

If the video has audio, moviepy will automatically process the audio part, and you can specify a different audio codec if needed.

Extended features

If you need to delete multiple time periods or perform more complex operations, you can split and merge them in the same way, and even add special effects, transition effects, etc.

If you have more complex needs for video editing, moviepy provides many other functions, such as cropping, transition effects, subtitles, etc., which can be explored further.

The above code is encapsulated into a function and modify the timestamp format to the minute and second format (for example, 2:30 represents 2 minutes and 30 seconds). We convert the time string to seconds and then use those seconds to edit the video.

Modified code

from  import VideoFileClip, concatenate_videoclips

def time_to_seconds(time_str):
    """
     Convert time in minute and second format to seconds
     For example: '2:30' -> 150 seconds
     """
    minutes, seconds = map(int, time_str.split(':'))
    return minutes * 60 + seconds

def delete_video_segment(input_video_path, output_video_path, start_time, end_time):
    """
     Delete the specified time period of the video and keep other parts
     :param input_video_path: Enter the video file path
     :param output_video_path: Output video file path
     :param start_time: The start time of the time period to be deleted (format: 'minute: seconds')
     :param end_time: The end time of the time period to be deleted (format: 'minute: seconds')
     """
    # Convert timestamp (minute and second format) to seconds    start_time_in_seconds = time_to_seconds(start_time)
    end_time_in_seconds = time_to_seconds(end_time)

    # Load video file    video = VideoFileClip(input_video_path)

    # Get the total length of the video    video_duration = 

    # Split video: Keep the two segments before and after deleting the segment    clip1 = (0, start_time_in_seconds)  # Start time from the start of the video to the beginning of the deleted segment    clip2 = (end_time_in_seconds, video_duration)  # From the end time of deleting segment to the end of the video
    # Merge the remaining parts    final_clip = concatenate_videoclips([clip1, clip2])

    # Write output video    final_clip.write_videofile(output_video_path, codec='libx264', audio_codec='aac')

# Example call:input_video_path = 'input_video.mp4'
output_video_path = 'output_video.mp4'
start_time = '1:30'  # For example, delete the section that starts at 1 minute and 30 secondsend_time = '3:00'    # Delete the part that ends at 3 minutes and 00 seconds
delete_video_segment(input_video_path, output_video_path, start_time, end_time)

Code parsing:

1.time_to_seconds function:

Converts a time string (for example '2:30') to seconds. By dividing the time into minutes and seconds using split(':'), then converting minutes into seconds and adding seconds, you end up with a timestamp in seconds.

2.delete_video_segment function:

The input parameters include the video path (input_video_path and output_video_path) and the time period to be deleted (start_time and end_time). The time parameter is passed in the 'minute:second' format.

The timestamp is converted to seconds by the time_to_seconds function for clipping of the video.

The video is divided into two parts: the part before the time period and the part after the time period is deleted, and then merge them.

Finally, use write_videofile to output the merged video as a new file.

Sample call:

Suppose you have a video file input_video.mp4 and want to delete the segment from 1:30 (1 minute 30) to 3:00 (3 minute 00).

After calling the delete_video_segment function, the output video is saved as output_video.mp4, where the specified part is deleted.

Notes:

Time format: The timestamp needs to be passed in minutes: seconds format (for example, 1:30 means 1 minute 30 seconds, and 3:00 means 3 minutes 00 seconds).

Video length: If the incoming timestamp exceeds the total video duration, moviepy will automatically process and avoid clips that are out of range.

Output file format: write_videofile supports multiple video formats, but make sure that appropriate codecs (such as libx264 and aac) are installed in your environment to ensure the correct encoding of video and audio.

You can further extend or modify the function as needed to handle more complex situations (such as deleting multiple time periods, etc.).

This is the article about deleting a certain piece of video in Python and retaining other time periods. For more related contents of deleting a certain piece of video in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!