The command getatime() in Python is different from the "Date Last Opened" in Finder (on macOS). How do I get the latter?

Viewed 79

I started working in Python (3.9) and wanted to use it to reorganize the fill on my computer (macOS Catalina v 10.15.7). To load the dates when the (mp4) files were last opened, I used: os.path.getatime(file_path) However, this date does not correspond to the date I find when looking at the file in Finder, neither does it correspond to the date when it was last modified or created, nor does it differ with a fixed amount. The loaded date seems to be a random date between now and when it was created. I would guess these dates are just determined in an other way, i.e. what counts as opening is different. Is there a way to get the date you see in Finder?


Found a solution: (credit to 3mpty)

Code to get the "Date Last Accessed" of the file Test.txt in my Documents folder

file_name = "Test.txt"
folder_path = "/Users/myName/Documents"
file_path = folder_path + "/" + file_name
file_Last_Opened = getDateLastAccessed(file_path_name)
print(file_Last_Opened)

def getDateLastAccessed(file_path_name):
    command = ['mdls', '-n', 'kMDItemLastUsedDate', file_name]
    output = subprocess.check_output(command).decode('utf-8')
    return output.split('=')[1].strip()

The function getDateLastAccessed returns a string with format "%Y-%m-%d %H:%M:%S %z", which can then be converted to a time object with time.strptime(...,"%Y-%m-%d %H:%M:%S %z").

1 Answers

MacOS uses metadata that cannot be accessed by usual os* package. To do it directly you have to use coreservices api and read: kMDItemLastUsedDate From python that can be achieved by pyobjc.

You can also try to workaround it by executing mdls tool and parsing output:

mdls file.txt | grep -m 1 kMDItemLastUsedDate

and in python:

import subprocess
command = 'mdls file.txt | grep -m 1 kMDItemLastUsedDate'
output = subprocess.check_output(command, shell = True).decode('utf-8')
date_str = output.split('=')[1].strip() # in example '2020-09-23 08:43:17 +0000'
Related