1

I am trying to write a script that changes the creation time of a file by increasing it by 10 seconds. I am testing it on Windows 7, but would also like to run it in XP. I tried to follow the solution from How do I change the file creation date of a Windows file from Python? with the following code:

import os
import pywintypes, win32file, win32con
def 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()


for (path, dirs, files) in os.walk('C:/Personal/fc/Images/Corvette'):
    for file in files:
        print(os.path.join(path, file))
        print(os.stat(os.path.join(path, file)))
        changeFileCreationTime(os.path.join(path, file),os.stat(os.path.join(path, file)).st_ctime+10)
        print(os.stat(os.path.join(path, file)))

but I get the error:

Traceback (most recent call last):
  File "C:\Python31\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
   exec(codeObject, __main__.__dict__)
  File "C:\Users\hermamr1\Desktop\Script1.py", line 20, in <module>
   changeFileCreationTime(os.path.join(path, file),os.stat(os.path.join(path, file)).st_ctime+10)
  File "C:\Users\hermamr1\Desktop\Script1.py", line 11, in changeFileCreationTime
   win32file.SetFileTime(winfile, wintime, None, None)
ValueError: astimezone() cannot be applied to a naive datetime

I am trying this on Python 3.1.3 but I can use Python 2.7 if needed. I will only need to run this on Windows.

Community
  • 1
  • 1
Michael
  • 1,321
  • 1
  • 13
  • 27
  • If your primary goal is to experiment with Python, especially PyWin32, then great. If you Just Need To Get It Done, then you might want to look into other means of changing the file creation date, such as PowerShell, AutoHotkey, or a precompiled executable utility (you can find freely downloadable ones). You can still use Python if you want, and call those other things with `os.system` or the `subprocess` module. – John Y Oct 09 '12 at 14:56

1 Answers1

1

It seems like implementation of astimezone() in python2.7 and python3 slightly differs. I tried to run your code under both of them, and only python3 raises ValueError. So, my solution is to switch to the python2.
Upd.: I'm not the only one who thinks that these implementations differs, you can take a look at following conversation (the second post from the bottom).

aga
  • 27,954
  • 13
  • 86
  • 121