Pierre Puiseux
Pierre Puiseux

Reputation: 1

setting st_birthtime in macOS

In macOS, I want to set st_birthtime to a date before 1970/01/01. For instance date = '1953/12/02 00:00:01'. N.B.st_birthtime is the fourth date displayed by shell command > stat my/file.txt I think it's also the date displayed by app Photos, and it can be set by Photos to a date < 1970/01/01.

If date is > 1970/01/01, code below (with Python objc package) gives the good result.

If date < 1970/01/01, i have fancyful results with code below.

My question is : how can I do it (without Photo app, of course) ?

# Thank to various AI :
from datetime import datetime, timezone
from Foundation import NSFileManager, NSDate, NSMutableDictionary
from path import Path

def set_birthtime(file_path:Path or str, birthtime:datetime):
    file_manager = NSFileManager.defaultManager()
    attributes = file_manager.attributesOfItemAtPath_error_(file_path, None)[0]
    mutable_attributes = NSMutableDictionary.dictionaryWithDictionary_(attributes)

    # Convert datetime to NSDate
    interval = birthtime - datetime(2001, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
    ns_date_birthtime = NSDate.dateWithTimeIntervalSinceReferenceDate_(interval.total_seconds())

    mutable_attributes['NSFileCreationDate'] = ns_date_birthtime
    file_manager.setAttributes_ofItemAtPath_error_(mutable_attributes, file_path, None)

if __name__ == '__main__':
    # Exemple d'utilisation
    file_path = Path('/Users/puiseux/Pictures/original.jpeg')
    birthtime = datetime(1973, 12, 2, 2, 12, 53, tzinfo=timezone.utc)
    debug("Ne fonctionne que si la date est > 1970-01-01")
    set_birthtime(file_path, birthtime)
    # verify result with shell command > stat original.jpeg

Upvotes: 0

Views: 13

Answers (0)

Related Questions