Skip to content

Instantly share code, notes, and snippets.

@ImSingee
Created May 7, 2018 04:43
Show Gist options
  • Save ImSingee/6d1a9552e9462cfa4344d8d1b364e0b0 to your computer and use it in GitHub Desktop.
Save ImSingee/6d1a9552e9462cfa4344d8d1b364e0b0 to your computer and use it in GitHub Desktop.
获取视频长度
import subprocess
def parse_second(second):
# https://gist.github.com/ImSingee/f1272ab376066749c2e0141d2f57c320
m, s = divmod(second, 60)
h, m = divmod(m, 60)
return "%02d:%02d:%02d" % (h, m, s)
def get_video_time(file_path, t=False):
# ffmpeg (ffprobe) required
# http://ffmpeg.org/
result = subprocess.Popen(["ffprobe",
"-loglevel", "quiet",
"-print_format", "json",
"-show_format",
file_path
],
stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
out, _ = result.communicate()
try:
seconds = round(float(json.loads(out)['format']['duration']), 2)
except:
seconds = 0
if t:
seconds = parse_second(seconds)
return seconds
if __name__ == '__main__':
PATH = 'input FILE PATH here'
print(get_video_time(PATH)) # seconds
print(get_video_time(PATH, t=True)) # hh:mm:ss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment