微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python-如何读取Windows“媒体创建”日期(而非文件创建日期)

我要转换几个旧的视频文件以节省空间.由于这些文件是个人视频,因此我希望新文件具有旧文件的创建时间.

Windows具有称为“媒体创建”的属性,该属性具有照相机记录的实际时间.文件修改时间通常不正确,因此有数百个文件无法使用.

如何在Python中访问“创建媒体”日期?我一直在疯狂地搜寻,找不到它.如果创建日期和修改日期匹配,下面是可以使用的代码示例:

files = []
for file in glob.glob("*.AVI"):
   files.append(file)

for orig in files:
    origmtime = os.path.getmtime(orig)
    origatime = os.path.getatime(orig)
    mark = (origatime, origmtime)
    for target in glob.glob("*.mp4"):
       firstroot = target.split(".mp4")[0]
       if firstroot in orig:
          os.utime(target, mark)

解决方法:

如Borealid所述,“创建的媒体”值不是文件系统元数据. Windows Shell从文件本身内部获取此值作为元数据.在API中可以将其作为Windows Property进行访问.如果您使用的是Windows Vista或更高版本并安装了Python extensions for Windows,则可以轻松访问Windows shell属性.只需致电SHGetPropertyStoreFromParsingName,您将在propsys模块中找到它.它返回一个PyIPropertyStore实例.标记为“已创建媒体”的属性System.Media.DateEncoded.您可以使用属性键PKEY_Media_DateEncoded(在propsys.pscon中找到)访问此属性.在Python 3中,返回的值是datetime.datetime子类,时间以UTC表示.在Python 2中,该值是一个自定义时间类型,其具有Format方法,该方法提供strftime样式格式.如果需要将值转换为本地时间,则pytz模块具有时区的IANA数据库.

例如:

import pytz
import datetime
from win32com.propsys import propsys, pscon

properties = propsys.SHGetPropertyStoreFromParsingName(filepath)
dt = properties.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()

if not isinstance(dt, datetime.datetime):
    # In Python 2, PyWin32 returns a custom time type instead of
    # using a datetime subclass. It has a Format method for strftime
    # style formatting, but let's just convert it to datetime:
    dt = datetime.datetime.fromtimestamp(int(dt))
    dt = dt.replace(tzinfo=pytz.timezone('UTC'))

dt_tokyo = dt.astimezone(pytz.timezone('Asia/Tokyo'))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐