Skip to content

Instantly share code, notes, and snippets.

@RhetTbull
Created September 9, 2025 12:10
Show Gist options
  • Select an option

  • Save RhetTbull/871a0ef7f66188349b70824b775f14d5 to your computer and use it in GitHub Desktop.

Select an option

Save RhetTbull/871a0ef7f66188349b70824b775f14d5 to your computer and use it in GitHub Desktop.
Set file creation date on macOS with python
#!/usr/bin/env python3
from datetime import datetime
from Foundation import NSURL, NSDate, NSURLCreationDateKey
def set_file_creation_date(file_path, creation_date):
"""
Sets the creation date of a file to the specified date
Args:
file_path (str): The file system path to the file
creation_date (datetime): The datetime to set as the new creation date
Returns:
bool: True if successful, False if an error occurred
"""
if not file_path or not creation_date:
print("Error: Invalid parameters - file_path and creation_date cannot be None")
return False
# Convert file path to NSURL
file_url = NSURL.fileURLWithPath_(file_path)
# Verify the file exists
exists, error = file_url.checkResourceIsReachableAndReturnError_(None)
if not exists:
print(f"Error: File does not exist at path: {file_path}")
return False
# Convert Python datetime to NSDate
# NSDate expects seconds since Jan 1, 2001 (NSDate reference date)
ns_date = NSDate.dateWithTimeIntervalSince1970_(creation_date.timestamp())
# Set the creation date using setResourceValue:forKey:error:
success, error = file_url.setResourceValue_forKey_error_(
ns_date, NSURLCreationDateKey, None
)
if not success:
error_msg = error.localizedDescription() if error else "Unknown error"
print(f"Error setting creation date: {error_msg}")
return False
return True
if __name__ == "__main__":
file_path = "test.txt"
new_creation_date = datetime(2020, 1, 1, 12, 0, 0)
if set_file_creation_date(file_path, new_creation_date):
print("Successfully updated creation date")
file_url = NSURL.fileURLWithPath_(file_path)
values, error = file_url.resourceValuesForKeys_error_(
[NSURLCreationDateKey], None
)
if creation_date := values.get(NSURLCreationDateKey):
# Convert NSDate back to Python datetime for display
timestamp = creation_date.timeIntervalSince1970()
readable_date = datetime.fromtimestamp(timestamp)
print(f"New creation date: {readable_date}")
else:
print("Failed to update creation date")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment