Skip to content

#120: Modify the Create Date of a File

I wanted to test a Python script that puts files into folders based on their creation time. But how can I create files in the past without using a time machine?

Install filedate

The Python package filedate is a great little helper when you need to read or write the different date attributes of a file. You can install it with this command:

pip install filedate

Read the date attributes of a file

With filedate you can read the creation date of a file, the modified date and, depending on the operating system, the last accessed date.

1
2
3
4
5
6
7
8
import filedate
from pathlib import Path

a = 'test_data/aa.txt'
Path(a).write_text("")

a_file = filedate.File(a)
print(a_file.get())

{'created': datetime.datetime(2022, 1, 1, 13, 0),

'modified': datetime.datetime(2022, 4, 18, 18, 56, 3, 945619),

'accessed': datetime.datetime(2022, 4, 18, 18, 56, 3, 945619)}

Change the date attributes of a file

While many Python libraries can read the date attributes of a file, filedate is the only one I know of that can change them:

import filedate

a = 'test_data/aa.txt'
a_file = filedate.File(a)

a_file.set(
    created = "2022.01.01 13:00:00",
    modified = "2022.01.01 14:00:00",
    accessed = "2022.01.01 15:00:00"
)

after = filedate.File(a)
print(after.get())

{'created': datetime.datetime(2022, 1, 1, 13, 0),

'modified': datetime.datetime(2022, 1, 1, 14, 0),

'accessed': datetime.datetime(2022, 1, 1, 15, 0)}

I suggest you use the ISO format (year-month-day) to set the dates. Although filedate can work with other date formats, the months and days may be interpreted differently than what you expect.

Especially in tests you should be as clear as you can be and prevent misunderstandings wherever possible.

Conclusion

I like the clear approach of filedate to change the creation date of my test files a lot more than mocking or patching the code involved with reading files. While changing the create date should not be a regular need, it is good to know that we can do that in Python if we must.