python获取文档的真实创建时间(word、excel、ppt、pdf、图片)

审题

首先,

文档的新建时间和文件的新建时间是不一致的。
文档的新建时间和文件的新建时间是不一致的。
文档的新建时间和文件的新建时间是不一致的。

文档的新建时间是和文件没有关系的(对word来说就是新建word的时间),而文件的时间是系统创建这个文件的时间(可能描述不准确)。具体来说文件的新建时间应该是操作系统维护的,但是每个类型的文档,其编辑器都是维护了一个文档描述信息在文件中,其是不随着文件的复制、移动所变更的。而我们就是需要获取文档的新建时间、而不是文件的新建时间。

获取文件的时间

具体获取文件的时间方法是使用os.path.getctime(filepath).还可以获取其他的时间,方法类似。

获取老版本office文件的时间

在处理这个需求最大的问题就是如何描述问题,当时能想到的描述方式都只搜到了获取文件时间的方法,最后在google搜索类似 获取word描述信息才找到方法。
具体当然很简单,pip安装 oletools包后就可以通过 olemeta [filename]获取文件的描述信息,就可以简单的获取文件的新建时间。

获取新版office文件的时间

尽管上一方法可以获取office文件的描述信息,但是却不能处理新版office文件(docx、xlsx、pptx)。但是知道了搜索方法、很快就能找到新版本office文件的处理方法。具体依靠:python-docx 、python-pptx、openpyxl三个包分别处理三种类型的office文档。
安装之后都可以使用类似的方法获取其描述信息(core_properties)

document = docx.Document(docx = path)
core_properties = document.core_properties
date=core_properties.created.strftime("%Y-%m-%d %H:%M")

获取pdf的时间

处理pdf使用 PyPDF2包,具体方法和之前的类似

from PyPDF2 import PdfFileReader
with open(path, 'rb') as f:
            pdf = PdfFileReader(f)
            if pdf.isEncrypted:
                pdf=pdf.decrypt('')
            info = pdf.getDocumentInfo()
        date=info['/CreationDate'][2:14]

TIPS
这里需要注意、获取的时间都是使用的UTC时间,还需要转换为东八区的时间。
代码见文件最后.

额外 照片处理

大概总结了一下,文档的时间获取之后,恰好也写一下照片日期的更改。
之前换手机的时候需要将照片全部同步到苹果的照片中,但是有很多照片导入进去后不是按照真正的时间排列的,修改照片的文件名也处理不了,最后捣鼓好久才知道修改照片exif文件中的拍摄时间。(exif中也包含地理信息)
由于exif时间使用了多个验证?更改了’0th’和’exif’中的时间.

from PIL import Image
import os
import piexif

PicList=['timewrong/%s'%_ for _ in os.listdir('timewrong') if 'DS_Store' not in _]
PicList.sort()
for _ in PicList:
    #只能处理jpeg格式的数据
    img = Image.open(_)
    # print(img.format)
    filename=_.split('/')[-1]
    year,month,day=filename.split('-')[:3]
    datestring=str.encode('%s:%s:%s 08:00:00'%(year,month,day))
    exif_dict={
    
    '0th': {
    
    306: datestring}, 'Exif': {
    
     36867: datestring, 36868: datestring}}
    print(exif_dict)
    exif_bytes = piexif.dump(exif_dict)
    img.save('new/%s'%filename, "jpeg", exif=exif_bytes)

文档时间代码

依赖的包

oletools
pypdf2
python-docx
python-pptx
openpyxl

扫描二维码关注公众号,回复: 11992590 查看本文章
"""
获取office文档和pdf的真实创建时间(在office和pdf编辑器里维护的tag,不随着复制而变更)
依赖python安装 oletools,pypdf2,import docx
"""
from PyPDF2 import PdfFileReader
import os
import time
import shutil
import docx
import pptx
from openpyxl import load_workbook
import datetime

def fix_date(timestr):
    """[增加8小时,变为北京时间]
    
    Arguments:
        timestr {[type]} -- [description]
    """
    newtime =datetime.datetime.strptime(timestr, "%Y-%m-%d %H:%M")+datetime.timedelta(hours=8)
    return newtime.strftime("%Y-%m-%d %H:%M")
    
def get_file_type(filename):
    '''
    获取文件的类型
    '''
    if '.pdf' == filename[-4:].lower():
        orginname=filename[:-4]
        return {
    
    'type':'pdf','orginname':orginname}
    elif '.doc' == filename[-4:].lower():
        orginname=filename[:-4]
        return {
    
    'type':'doc','orginname':orginname}
    elif '.docx' == filename[-5:].lower():
        orginname=filename[:-5]
        return {
    
    'type':'docx','orginname':orginname}
    
    elif '.ppt' == filename[-4:].lower():
        orginname=filename[:-4]
        return {
    
    'type':'ppt','orginname':orginname}
    elif '.pptx' == filename[-5:].lower():
        orginname=filename[:-5]
        return {
    
    'type':'pptx','orginname':orginname}
    
    elif '.xls' == filename[-4:].lower():
        orginname=filename[:-4]
        return {
    
    'type':'xls','orginname':orginname}
    elif '.xlsx' == filename[-5:].lower():
        orginname=filename[:-5]
        return {
    
    'type':'xlsx','orginname':orginname}
        
    elif '.txt' == filename[-4:].lower():
        orginname=filename[:-4]
        return {
    
    'type':'txt','orginname':orginname}
    
    else:
        return {
    
    'type':'None','orginname':'None'}

def get_os_date(path):
    """获取path的time
    
    Arguments:
        path {[type]} -- [description]
    """
    return time.strftime("%Y-%m-%d %H:%M", time.localtime(os.path.getctime(path)))
    
def get_pdf_date(path):
    """[获取pdf类型文件的时间]
    
    Arguments:
        path {[type]} -- [description]
    
    Returns:
        [type] -- [时间字符串]
    """
    try:
        with open(path, 'rb') as f:
            pdf = PdfFileReader(f)
            if pdf.isEncrypted:
                pdf=pdf.decrypt('')
            info = pdf.getDocumentInfo()
        date=info['/CreationDate'][2:14]
        res='%s-%s-%s %s:%s'%(date[:4],date[4:6],date[6:8],date[8:10],date[10:12])
        return fix_date(res)
    except:
        return get_os_date(path)
    
def get_docx_date(path):
    """[获取docx类型文件的时间]
    
    Arguments:
        path {[type]} -- [description]
    
    Returns:
        [type] -- [时间字符串]
    """
    try:
        document = docx.Document(docx = path)
        core_properties = document.core_properties
        date=core_properties.created.strftime("%Y-%m-%d %H:%M")
        return fix_date(date)
    except:
        return get_os_date(path)
    
def get_pptx_date(path):
    """[获取docx类型文件的时间]
    
    Arguments:
        path {[type]} -- [description]
    
    Returns:
        [type] -- [时间字符串]
    """
    try:
        prs = pptx.Presentation(path)
        core_properties = prs.core_properties
        date=core_properties.created.strftime("%Y-%m-%d %H:%M")
        return fix_date(date)
    except:
        return get_os_date(path)
    
def get_xlsx_date(path):
    """[获取xlsx类型文件的时间]
    
    Arguments:
        path {[type]} -- [description]
    
    Returns:
        [type] -- [时间字符串]
    """
    try:
        wb = load_workbook(path)
        date=wb.properties.created.strftime("%Y-%m-%d %H:%M")
        return fix_date(date)
    except:
        return get_os_date(path)
 
def get_office_file_date(path):
    """[获取office类型文件的时间]
    Arguments:
        path {[type]} -- [description]
    Returns:
        [type] -- [时间字符串]
    """
    try:
        result = os.popen('olemeta %s'%(path))  
        res = result.read() 
        for line in res.split('\n'):
            if '|create_time' in line:
                date=line.split('|')[2]
                date=date[:16]
        return fix_date(date)
    except:
        return get_os_date(path)    
    
def get_file_time(path):
    """[获取文件的时间]调用各个类型的获取方法
    
    Arguments:
        path {[type]} -- [description]
    """ 
    
    filetype=get_file_type(path)['type']
    try:
        if filetype=='pdf':
            shutil.copy(path,'temp/temp.pdf')
            filetime=get_pdf_date('temp/temp.pdf')
            os.remove('temp/temp.pdf')
            return filetime
        
        elif filetype in ['docx']:
            shutil.copy(path,'temp/temp.%s'%(filetype))
            filetime= get_docx_date('temp/temp.%s'%(filetype))
            os.remove('temp/temp.%s'%(filetype))
            return filetime
        
        elif filetype in ['pptx']:
            shutil.copy(path,'temp/temp.%s'%(filetype))
            filetime= get_pptx_date('temp/temp.%s'%(filetype))
            os.remove('temp/temp.%s'%(filetype))
            return filetime
        
        elif filetype in ['xlsx']:
            shutil.copy(path,'temp/temp.%s'%(filetype))
            filetime= get_xlsx_date('temp/temp.%s'%(filetype))
            os.remove('temp/temp.%s'%(filetype))
            return filetime
        
        
        elif filetype in ['doc','ppt','xls']:
            shutil.copy(path,'temp/temp.%s'%(filetype))
            filetime= get_office_file_date('temp/temp.%s'%(filetype))
            os.remove('temp/temp.%s'%(filetype))
            return filetime
        else:
            return get_os_date(path)
    except:
        return time.strftime("%Y-%m-%d %H:%M", time.localtime())

# print(get_file_time('/Users/leeber/Desktop/test.pdf'))

github主页 欢迎关注

猜你喜欢

转载自blog.csdn.net/lovoslbdy/article/details/103114438