Skip to content

Instantly share code, notes, and snippets.

@birkin
Created May 17, 2023 19:00
Show Gist options
  • Save birkin/d4f095b658e7f1004b87a58f3d020f0b to your computer and use it in GitHub Desktop.
Save birkin/d4f095b658e7f1004b87a58f3d020f0b to your computer and use it in GitHub Desktop.
setting a file's creation-&-modification date via python.

Prompt

using python, how would I change a file creation-date for a pdf?


Response

Modifying a file's creation time isn't a standard operation because it's not a common need and it can potentially cause issues. However, it is possible to do this using the Python os and datetime modules, specifically using the os.utime function.

Here is a basic example of how you can change the creation date of a file:

import os
import time
import datetime

# specify your file path
filepath = '/path/to/your/file.pdf'

# specify the creation date you want to set
new_creation_time = datetime.datetime(2023, 5, 17, 0, 0)

# convert the datetime object to a timestamp
new_timestamp = time.mktime(new_creation_time.timetuple())

# change the creation date of the file
os.utime(filepath, (new_timestamp, new_timestamp))

In this example, the creation time and modification time of the file at filepath are set to the timestamp equivalent of May 17, 2023, at 00:00.

Please note:

  1. The os.utime function changes both the access time and the modified time. As far as I know, there's no standard way in Python to change only the creation time of a file.
  2. This method will work on Unix systems (like Linux or MacOS). On Windows, it might not work as expected because Windows handles file timestamps differently. For Windows, you might need to use a platform-specific API to modify the creation time, such as pywin32.
  3. Changing file timestamps can have unexpected side effects, like affecting backups or causing issues with file synchronization, so it's generally not recommended unless you have a specific reason for doing it.
  4. Make sure you have the appropriate permissions to modify the file.

(chatgpt-4, 2023-May-17)


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment