Home > OS >  How to get the start time, end time in seconds from YouTube timestamp using python?
How to get the start time, end time in seconds from YouTube timestamp using python?

Time:11-13

I'm having a list of timestamps of a YouTube video.

Example:

timestamps = ['0:02-0:35', '0:50-1:18', '2:53-3:08', '3:12-3:14', '3:16-3:22', '3:25-3:28', '1:09-1:35', '1:38-1:48', '2:04-2:14', '2:30-2:40', '2:45-2:50', '3:35-4:07', '4:16-4:22', '4:48-4:54', '5:00-5:12', '5:34-5:54', '8:58-9:19', '']

Now I need to fetch the starttime and endtime for each timestamp in seconds since I need to pass these as arguments for ffmpeg_extract_subclip method to cut a video into sub clips.

for example,

# If the timestamp is 0:02-0:35 The starttime and endtime should be,
timestamp = '0:02-0:35'
starttime = 2
endtime = 35

# If the timestamp is 3:02-3:35 The starttime and endtime should be,
timestamp = '3:02-3:35'
starttime = 182 # [(3 * 60)   2]
endtime = 215 # [(3 * 60)   35]

Can we do it with regex? or Is there any other options?

CodePudding user response:

You can do it with regex, capturing the minutes (\d{1,2}) and seconds(\d{2}) from the source string.

import re
interval = '0:02-0:35'
start_min, start_sec, end_min, end_sec = map(int, re.findall('\d{1,2}', interval))

or split time by : and - via re.split.

start_min, start_sec, end_min, end_sec = map(int, re.split('[:-]', interval))

But you can also simply do it by a built-in function str.split.

start_min, start_sec, end_min, end_sec = (int(t) for time in interval.split('-') for t in time.split(':'))
  • Related