您当前的位置:首页 > 计算机 > 编程开发 > Python

获取视频时长和文件大小

时间:07-10来源:作者:点击数:

获取视频时长和文件大小

import os
from moviepy.editor import VideoFileClip
import pymysql
 
file_dir = ".\\video"  # 定义文件目录
 
 
class FileCheck(object):
 
    def __init__(self):
        self.file_dir = file_dir
 
    def get_filesize(self, filename):
        u"""
        获取文件大小(M: 兆)
        """
        file_byte = os.path.getsize(filename)
        return self.sizeConvert(file_byte)
 
    def get_file_times(self, filename):
        u"""
        获取视频时长(s:秒)
        """
        clip = VideoFileClip(filename)
        print(clip.duration)
        file_time = self.timeConvert(clip.duration)
        clip.reader.close()
        clip.audio.reader.close_proc()
        return file_time
 
    def sizeConvert(self, size):  # 单位换算
        K, M, G = 1024, 1024 ** 2, 1024 ** 3
        if size >= G:
            return str(size / G) + 'G Bytes'
        elif size >= M:
            return str(size / M) + 'M Bytes'
        elif size >= K:
            return str(size / K) + 'K Bytes'
        else:
            return str(size) + 'Bytes'
 
    def timeConvert(self, size):  # 单位换算
        M, H = 60, 60 ** 2
        if size < M:
            return '%s:%s:%s'%('00', '00', '%02d' % int(size))
        if size < H:
            return '%s:%s:%s' % ('00', '%02d' % int(size / M), '%02d' % int(size % M))
        else:
            hour = '%02d' % int(size / H)
            mine = '%02d' % int(size % H / M)
            second = '%02d' % int(size % H % M)
            tim_srt = '%s:%s:%s' % (hour, mine, second)
            return tim_srt
 
 
class video_time(object):
    def __init__(self):
        # self.db = pymysql.connect(host='localhost', port=3306, database='abc', user='root',
        #                           password='root',
        #                           charset='utf8')
        self.db = pymysql.connect(host='115.238.111.198', port=3306, database='spider_yu', user='spider',
                                  password='Kangce@0608', charset='utf8')
        self.cursor = self.db.cursor()
 
        self.video_time()
 
    def video_time(self):
        videos = FileCheck()
        video_list = os.listdir(file_dir)
        for video_name in video_list:
            names = '.\\video\\' + video_name
            video_time = videos.get_file_times(names)
            print(video_name)
            if '.' in video_time:
                video_time = video_time.split('.')[0]
            self.cursor.execute(
                'update youjiankang set videoTime="{}" where videoUrl="{}"'.format(video_time, video_name))
            self.db.commit()
            print('video_time', video_time)
 
 
if __name__ == "__main__":
    video_time()

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门