How do I change the file creation date of a Windows file?
Yak shaving for the win.
import pywintypes, win32file, win32condef changeFileCreationTime(fname, newtime): wintime = pywintypes.Time(newtime) winfile = win32file.CreateFile( fname, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) win32file.SetFileTime(winfile, wintime, None, None) winfile.close()
I did not want to bring the whole pywin32
/ win32file
library solely to set the creation time of a file, so I made the win32-setctime
package which does just that.
pip install win32-setctime
And then use it like that:
from win32_setctime import setctimesetctime("my_file.txt", 1561675987.509)
Basically, the function can be reduced to just a few lines without needing any dependency other that the built-in ctypes
Python library:
from ctypes import windll, wintypes, byref# Arbitrary example of a file and a datefilepath = "my_file.txt"epoch = 1561675987.509# Convert Unix timestamp to Windows FileTime using some magic numbers# See documentation: https://support.microsoft.com/en-us/help/167296timestamp = int((epoch * 10000000) + 116444736000000000)ctime = wintypes.FILETIME(timestamp & 0xFFFFFFFF, timestamp >> 32)# Call Win32 API to modify the file creation datehandle = windll.kernel32.CreateFileW(filepath, 256, 0, None, 3, 128, None)windll.kernel32.SetFileTime(handle, byref(ctime), None, None)windll.kernel32.CloseHandle(handle)
For advanced management (like error handling), see the source code of win32_setctime.py
.
install pywin32 extension first https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/
import win32fileimport pywintypes# main logic functiondef changeFileCreateTime(path, ctime): # path: your file path # ctime: Unix timestamp # open file and get the handle of file # API: http://timgolden.me.uk/pywin32-docs/win32file__CreateFile_meth.html handle = win32file.CreateFile( path, # file path win32file.GENERIC_WRITE, # must opened with GENERIC_WRITE access 0, None, win32file.OPEN_EXISTING, 0, 0 ) # create a PyTime object # API: http://timgolden.me.uk/pywin32-docs/pywintypes__Time_meth.html PyTime = pywintypes.Time(ctime) # reset the create time of file # API: http://timgolden.me.uk/pywin32-docs/win32file__SetFileTime_meth.html win32file.SetFileTime( handle, PyTime )# examplechangeFileCreateTime('C:/Users/percy/Desktop/1.txt',1234567789)