Chris
Chris

Reputation: 111

Change creation time in file in Python3

I am trying to change the date of creation of a file in Windows, I am doing it in python 3.6. The problem is that the date of creation does not change by the date "2006-06-06 00:00:00", I receive as a result the date "August 21, 1970".

Code :

from datetime import datetime
import pywintypes, win32file, win32con

def convert_to_datetime(date):
    datetime_object = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    return datetime_object

def convert_to_integer(dt_time):
    return 10000*dt_time.year + 100*dt_time.month + dt_time.day

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()

#

date_convert = convert_to_datetime("2006-06-06 00:00:00")
date_int = convert_to_integer(date_convert)

changeFileCreationTime("test.txt",date_int)

How do I fix this error?

Upvotes: 2

Views: 3675

Answers (1)

Laurent H.
Laurent H.

Reputation: 6526

Your function convert_to_integer returns 20060606, which indeed is August 21th, 1970 in number of seconds elapsed since 1970.

You should instead use the method datetime.timestamp()

Upvotes: 3

Related Questions