Python установить дату создания файла

Как изменить дату создания файла Windows из Python?

@Claudiu: я опубликовал это для читателей, которые ищут в Google «python change file date windows» . Ваш вопрос — вторая ссылка.

6 ответов

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

Если вы получили ImportError и задаетесь вопросом, где можно найти pywintypes (как я это сделал): sourceforge.net/projects/pywin32

Этот код работает на python 3 без 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() 

@Vlad это ошибка при использовании неверных операторов импорта. Объектом является datetime.datetime, как в моем примере, а не datetime.datetime.datetime, как вы пытаетесь его использовать.

Вы правы — я изменил оператор импорта, но теперь ошибка является a float is required для datetime.datetime.utcfromtimestamp(newtime) . Было бы здорово иметь эту работу в Python 3.

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) 

Почему так сложно узнать, что win32file является частью pywin32 ? Google оставил меня в покое и сухости, что означало, что ни один из других ответов не был вообще полезным; они предполагали, что вы уже установили его. Спасибо за полезный совет в верхней части вашего ответа.

Читайте также:  Html padding top right bottom left

PS Любой, кому нужна временная метка от объекта datetime может найти ответ здесь: stackoverflow.com/q/7852855/5987

Вот решение, которое работает на Python 3.5 и Windows 7. Очень просто. Я признаю это небрежным кодированием. но он работает. Вы можете его очистить. Мне просто нужен был быстрый солн.

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 ) 

Здесь более надежная версия принятого ответа. Он также имеет противоположную функцию геттера. Эти адреса создавали, изменяли и получали доступ к датам. Он обрабатывает параметры datetimes, предоставляемые как объекты datetime.datetime, так и как «секунды с эпохи» (что возвращает геттер). Кроме того, он регулирует время дневного света, на которое не отвечает принятый ответ. Без этого ваши времена не будут установлены правильно, если вы установите зимнее или летнее время в течение противоположной фазы вашего фактического системного времени.

Основная слабость этого ответа заключается в том, что он предназначен только для Windows (который отвечает на поставленный вопрос). В будущем я постараюсь разместить кросс-платформенное решение.

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 

Источник

Получение даты создания и изменения файла в Python

Существуют случаи, когда возникает потребность получить информацию о дате создания и последнего изменения файла. Это может быть полезно во многих контекстах, например, при создании скриптов для автоматического архивирования файлов или при работе с системами управления версиями.

В Python есть несколько способов получить эту информацию, причем большинство из них являются кросс-платформенными и будут работать как на Linux, так и на Windows.

Самый простой и распространенный способ — использование встроенного модуля os . Этот модуль содержит функцию os.path.getmtime() , которая возвращает время последнего изменения файла в виде числа с плавающей точкой, представляющего секунды с начала эпохи (обычно это 01.01.1970 г.).

import os filename = "test.txt" mtime = os.path.getmtime(filename) print(mtime)

Этот код вернет время последнего изменения файла «test.txt». Чтобы преобразовать это время из секунд с начала эпохи в более читаемый формат, можно использовать функцию datetime.fromtimestamp() :

import os from datetime import datetime filename = "test.txt" mtime = os.path.getmtime(filename) mtime_readable = datetime.fromtimestamp(mtime) print(mtime_readable)

Получение времени создания файла немного сложнее и отличается в зависимости от операционной системы. На Windows можно использовать функцию os.path.getctime() , которая работает аналогично os.path.getmtime() , но возвращает время создания файла. На Linux, к сожалению, такой функции нет, поэтому придется использовать функцию os.stat() , которая возвращает объект с метаданными файла, включая время его создания.

import os from datetime import datetime filename = "test.txt" stat = os.stat(filename) ctime = stat.st_ctime ctime_readable = datetime.fromtimestamp(ctime) print(ctime_readable)

Таким образом, получение информации о времени создания и изменения файла в Python — это относительно простая задача, которая может быть выполнена с помощью встроенного модуля os .

Источник

Change File Modification Time In Python

This post demonstrates how to change a file modification time in Python. No third party modules are required and it will work on Windows, Mac and Linux.

File modification times show when a file was last edited. This can sometimes be confused with creation time but these are very different. Creation time is normally held by the operating system and states when a file was created. This means if you download a file from the internet, the creation time will change and be the time it was downloaded. Thus the creation time isn’t very helpful.

File modification time is different however as it is stored in the file. Even though the operating system still manages these, they can still be easily changed as opposed to creation time.

The modification date can be found by right-clicking on a file and selecting properties.

Properties showing times of a file

Setting File Modification Times

First, you will want to import os, time and datetime.

import os import time import datetime 

You will now need to locate the file you want to edit and create a time object to set to the file. To create one, we will first break it down into its simpler parts.

fileLocation = r"" year = 2017 month = 11 day = 5 hour = 19 minute = 50 second = 0 

fileLocation is a string and the rest of the variables above are integers.

Next, we will create our datetime object using the data given and then convert it to seconds since epoch; this is what will be stored.

date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second) modTime = time.mktime(date.timetuple()) 

Now we can do a simple os.utime call passing the file and modification time to set the new times.

os.utime(fileLocation, (modTime, modTime)) 

Now if you go back and check the modification date it should be changed.

import os import time import datetime fileLocation = r"" year = 2017 month = 11 day = 5 hour = 19 minute = 50 second = 0 date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second) modTime = time.mktime(date.timetuple()) os.utime(fileLocation, (modTime, modTime)) 

But how do I change creation time?

The solution is platform-specific but for Windows you can look at this.

Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.

Источник

Оцените статью