使用 pdfminer 解析 pdf 元数据日期

parse pdf metadata date using pdfminer

我正在尝试获取 pdf 文件的元数据

from pdfminer3.pdfparser import PDFParser
from pdfminer3.pdfdocument import PDFDocument
fp = open('C:/Users/asus/Desktop/storage/jdghosh_sap@rediffmail.com.pdf', 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)
print(doc.info[0]["CreationDate"])
print(doc.info[0]["ModDate"])

输出

b"D:20140706114446+05'30'"
b"D:20140706114446+05'30'"

如何将此数据解析为 python 日期?

做了一个转换它的小函数:

from pdfminer3.pdfparser import PDFParser
from pdfminer3.pdfdocument import PDFDocument

def convertPdfDatetime(pd):
    from datetime import datetime
    dtformat = "%Y%m%d%H%M%S"
    clean = pd.decode("utf-8").replace("D:","").split('+')[0]
    return datetime.strptime(clean,dtformat)

fp = open('/home/prtjohanson/test.pdf', 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser)
pdf_creation_date = doc.info[0]["CreationDate"]
print(pdf_creation_date)
print(convertPdfDatetime(pdf_creation_date))

出于某种原因,在我的 linux 机器上,我没有在日期时间字符串末尾以 + 开头的后缀,我怀疑它可能与时区有关,或者可能取决于pdf 文件本身是如何创建的。

无论如何,上面的代码应该涵盖这两种情况。