如何用Python获取Windows系统中文件的源内容创建日期?
获取Windows文件的“源内容创建日期”(内置包实现)
你提到的“源内容创建日期”属于文件的扩展元数据,和pathlib提供的文件系统层面时间(创建/修改时间)无关。在Windows系统下,可以通过内置的ctypes模块调用系统API来获取这类元数据,无需额外安装第三方包。
实现代码
import ctypes from ctypes import wintypes import datetime # 初始化COM库 ctypes.OleInitialize(None) # 定义所需的Windows API结构和函数 class PROPERTYKEY(ctypes.Structure): _fields_ = [ ("fmtid", wintypes.GUID), ("pid", wintypes.DWORD) ] class PROPVARIANT(ctypes.Structure): _fields_ = [ ("vt", wintypes.WORD), ("wReserved1", wintypes.WORD), ("wReserved2", wintypes.WORD), ("wReserved3", wintypes.WORD), ("data", ctypes.c_void_p) ] # 绑定Shell32中的函数 shell32 = ctypes.WinDLL("shell32") propsys = ctypes.WinDLL("propsys") SHGetPropertyStoreFromParsingName = shell32.SHGetPropertyStoreFromParsingName SHGetPropertyStoreFromParsingName.argtypes = [ wintypes.LPCWSTR, wintypes.LPCVOID, wintypes.DWORD, wintypes.REFIID, ctypes.POINTER(ctypes.c_void_p) ] SHGetPropertyStoreFromParsingName.restype = wintypes.HRESULT IPropertyStore_GetValue = propsys.IPropertyStore_GetValue IPropertyStore_GetValue.argtypes = [ ctypes.c_void_p, ctypes.POINTER(PROPERTYKEY), ctypes.POINTER(PROPVARIANT) ] IPropertyStore_GetValue.restype = wintypes.HRESULT IPropertyStore_Release = propsys.IPropertyStore_Release IPropertyStore_Release.argtypes = [ctypes.c_void_p] IPropertyStore_Release.restype = None PropVariantClear = propsys.PropVariantClear PropVariantClear.argtypes = [ctypes.POINTER(PROPVARIANT)] PropVariantClear.restype = wintypes.HRESULT # 定义“源内容创建日期”对应的PROPERTYKEY # 对应System.Media.DateCreated属性,PID为10 MEDIA_CREATION_DATE_PK = PROPERTYKEY( fmtid=wintypes.GUID("{64440490-4C8B-11D1-8B70-080036B11A03}"), pid=10 ) def get_media_creation_date(file_path): ps = ctypes.c_void_p() hr = SHGetPropertyStoreFromParsingName( str(file_path), None, 0, wintypes.GUID("{886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99}"), # IPropertyStore的IID ctypes.byref(ps) ) if hr != 0: return None pv = PROPVARIANT() hr = IPropertyStore_GetValue(ps, ctypes.byref(MEDIA_CREATION_DATE_PK), ctypes.byref(pv)) if hr != 0: IPropertyStore_Release(ps) return None # 解析DATE类型的PropVariant if pv.vt == 7: # VT_DATE # DATE类型是双精度浮点数,代表自1899-12-30以来的天数 date_val = ctypes.cast(pv.data, ctypes.POINTER(ctypes.c_double)).contents.value creation_date = datetime.datetime(1899, 12, 30) + datetime.timedelta(days=date_val) result = creation_date.replace(microsecond=0) else: result = None PropVariantClear(ctypes.byref(pv)) IPropertyStore_Release(ps) return result # 使用示例 if __name__ == "__main__": file_path = r"C:\example.mp4" # 替换为你的文件路径 creation_date = get_media_creation_date(file_path) if creation_date: print(f"源内容创建日期: {creation_date}") else: print("无法获取源内容创建日期(文件不支持该元数据或系统错误)") # 释放COM库 ctypes.OleUninitialize()
说明
- 这段代码仅适用于Windows系统,因为依赖Windows Shell API获取文件元数据
- 并非所有文件都包含“源内容创建日期”元数据——只有媒体文件(视频、图片)、Office文档等带有内容创建信息的文件才会存储该字段
- 代码中使用的
PROPERTYKEY对应Windows系统定义的System.Media.DateCreated属性,是文件属性页中“源内容创建日期”的底层标识
内容的提问来源于stack exchange,提问作者Javid Shiriyev
相关产品推荐
相关产品推荐

