How to Trim a Video using Python?

Video trimming involves eliminating irrelevant or redundant segments from your video material. It allows you to slice a video at specific moments for removing certain sections of the video, such as the initial seconds, or to split the video into separate files. To achieve this in Python, you can use a video editing API. Here's a simple and straightforward method to trim videos with just a few lines of code:

Input Code
import requests

json = {
 'source': {
  'output_format': 'mp4',
  'elements': [
   {
    'type': 'video',
    'source': 'https://cdn.creatomate.com/demo/mountains.mp4',
    'trim_start': 1,
    'trim_duration': 3
   }
  ]
 }
}

response = requests.post(
 'https://api.creatomate.com/v1/renders',
 headers={
  # Find your API key under 'Project Settings' in your account:
  # https://creatomate.com/docs/api/rest-api/authentication
  'Authorization': 'Bearer Your-API-Key',
  'Content-Type': 'application/json',
 },
 json=json
)

# Wait a minute, then visit the URL provided in the response:
print(response.json())

Output Video

How it works: You don't need to install any dependencies, since all you need is the standard Python "requests" library. As seen in this example, we are dealing with a single video within the scene. It is possible to specify any publicly hosted URL regardless of its format, in which case the API automatically converts it to MP4.

To actually trim the video, you can use the "trim_start" and "trim_duration" properties to specify the timestamps at which the video should be cut. In this case, we are slicing the video starting from 1 second at the beginning and preserving a maximum duration of 3 seconds.

For more advanced video editing tasks, try out the code video editor tool as well. This online tool not only enables you to programmatically trim videos but also simplifies a wide range of video editing tasks required for Python video processing. Feel free to check it out below.

Edit this Code Example in the Video Editor

Easily design your own video templates using the online editor. Then, export your templates as JSON and integrate them into your Python application to create any kind of video – completely through code.

Related Python Video Editing Questions

Start automating today

Start with a full-featured trial with 50 credits, no credit card required.
Get started for free