Trying to get "Media created" timestamp and insert as the "Last modified date" with python for .mp4 and .m4a video, audio files (no EXIF). The "Media created" timestamp shows up and correctly in Windows with right click file inspection, but I can not get it with python. What am I doing wrong? (This is also a working fix for cloud storage changing the last modified date of files.)
enter from mutagen.mp4 import MP4, M4A
from datetime import datetime
import os
def get_mp4_media_created_date(filepath):
"""
Extracts the "Media Created" date from an MP4 or M4A file.
Args:
filepath (str): The path to the MP4 or M4A file.
Returns:
datetime or None: The creation date as a datetime object, or None if not found.
"""
file_lower = filepath.lower()
try:
if file_lower.endswith(".mp4"):
media = MP4(filepath)
elif file_lower.endswith(".m4a"):
media = M4A(filepath)
else:
return None # Not an MP4 or M4A file
found_date = None
date_tags_to_check = ['creation_time', 'com.apple.quicktime.creationdate']
for tag in date_tags_to_check:
if tag in media:
values = media[tag]
if not isinstance(values, list):
values = [values]
for value in values:
if isinstance(value, datetime):
found_date = value
break
elif isinstance(value, str):
try:
found_date = datetime.fromisoformat(value.replace('Z', '+00:00'))
break
except ValueError:
pass
if found_date:
break
return found_date
except Exception as e:
print(f"Error processing {filepath}: {e}")
return None
if __name__ == "__main__":
filepath = input("Enter the path to the MP4/M4A file: ")
if os.path.exists(filepath):
creation_date = get_mp4_media_created_date(filepath)
if creation_date:
print(f"Media Created Date: {creation_date}")
else:
print("Could not find Media Created Date.")
else:
print("File not found.")
here
As described here, the "Media created" value is not filesystem metadata. It's accessible in the API as a Windows Property.
You can use os.utime
to set "Media created" timestamp as the "Last modified date". Like
import pytz
import datetime
import os
from win32com.propsys import propsys, pscon
file = 'path/to/your/file'
properties = propsys.SHGetPropertyStoreFromParsingName(file)
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'))
print('Media created at', dt, dt.timestamp())
os.utime(file, (dt.timestamp(),dt.timestamp()))