Hvordan ændrer jeg filens oprettelsesdato for en Windows-fil fra Python?

Indlæg af Hanne Mølgaard Plasc

Problem



Hvordan ændrer jeg filens oprettelsesdato for en Windows-fil fra Python?

Bedste reference


Yak barbering til sejren. [8]


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

Andre referencer 1


Denne kode fungerer på python 3 uden
ValueError: astimezone() cannot be applied to a naive datetime:


wintime = datetime.datetime.utcfromtimestamp(newtime).replace(tzinfo=datetime.timezone.utc)
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)
winfile.close()

Andre referencer 2


import os
os.utime(path, (accessed\_time, modified\_time))


http://docs.python.org/library/os.html[9]

Andre referencer 3



   Installer pywin32 udvidelse først https://sourceforge.net/projects/pywin32/files/pywin32/Build\%20221/[10]



import win32file
import pywintypes

# main logic function
def 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
    )

# example
changeFileCreateTime('C:/Users/percy/Desktop/1.txt',1234567789)

Andre referencer 4


Her er en mere robust version af det accepterede svar. Det har også den modsatte getter-funktion.Denne adresser er oprettet, ændret og fået adgang til datatimer. Den håndterer at have datetime-parametrene angivet som enten datetime.datetime objekter eller som 'sekunder siden epoken '(hvad getter vender tilbage). Endvidere justerer det sig for Day Light Saving tid, hvilket det accepterede svar ikke gør. Uden det bliver dine tider ikke indstillet korrekt, når du indstiller en vinter eller sommer tid i den modsatte fase af din faktiske system tid.


Den største svaghed ved dette svar er, at det kun er til Windows (hvilket svarer spørgsmålet). I fremtiden vil jeg forsøge at sende en cross platform løsning.


def isWindows() :
  import platform
  return platform.system() == 'Windows' 

def getFileDateTimes( filePath ):        
    return ( os.path.getctime( filePath ), 
             os.path.getmtime( filePath ), 
             os.path.getatime( filePath ) )

def setFileDateTimes( filePath, datetimes ):
    try :
        import datetime
        import time 
        if isWindows() :
            import win32file, win32con
            ctime = datetimes[0]
            mtime = datetimes[1]
            atime = datetimes[2]
            # handle datetime.datetime parameters
            if isinstance( ctime, datetime.datetime ) :
                ctime = time.mktime( ctime.timetuple() ) 
            if isinstance( mtime, datetime.datetime ) :
                mtime = time.mktime( mtime.timetuple() ) 
            if isinstance( atime, datetime.datetime ) :
                atime = time.mktime( atime.timetuple() )             
            # adjust for day light savings     
            now = time.localtime()
            ctime += 3600 * (now.tm\_isdst - time.localtime(ctime).tm\_isdst)
            mtime += 3600 * (now.tm\_isdst - time.localtime(mtime).tm\_isdst)
            atime += 3600 * (now.tm\_isdst - time.localtime(atime).tm\_isdst)            
            # change time stamps
            winfile = win32file.CreateFile(
                filePath, 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, ctime, atime, mtime )
            winfile.close()
        else : """MUST FIGURE OUT..."""
    except : pass    

Andre referencer 5


Her er en løsning, der fungerer på Python 3.5 og Windows 7. Meget let. Jeg indrømmer det slemme kodning ... men det virker. Du er velkommen til at rydde den op. Jeg havde lige brug for en hurtig soln.





import pywintypes, win32file, win32con, datetime, pytz

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,  wintime,     wintime)
    # None doesnt change args = file,     creation, last access, last write
    # win32file.SetFileTime(None, None, None, None) # does nonething
    winfile.close()

if \_\_name\_\_ == "\_\_main\_\_":
    local\_tz = pytz.timezone('Antarctica/South\_Pole')
    start\_date = local\_tz.localize(datetime.datetime(1776,7,4), is\_dst=None)
    changeFileCreationTime(r'C:homemade.pr0n', start\_date )