- How to get file creation & modification date/times in Python?
- Using OS Module: File Creation Time On Windows
- Example
- Output
- Using OS Module: File Modification Time On Windows
- Example
- Output
- Using OS Module: File Modification Time On MAC AND UNIX
- Example
- Output
- Using OS Module: File Modification Time On MAC AND UNIX
- Example
- Output
- Using Pathlib Module: File Creation Time On Windows
- Example
- Output
- Using Pathlib Module: File Modification Time On Windows
- Example
- Output
- Получение даты создания и изменения файла в Python
- Get file creation & modification date time
How to get file creation & modification date/times in Python?
They are various ways to get the file creation and modification datetime in python. We will use different methods from the OS and pathlib module to get the file creation and modification datetime in python.
Using OS Module: File Creation Time On Windows
Here we have used the OS module to find the creation time of a file. Initially, we need to import OS module and datetime module. The OS module is used for getting the timestamp whereas the datetime module is used for creating a datetime object. os.path.getctime(‘path’) function is used to get the creation time of a file. The os.path.getctime(‘path’) returns the creation time in numeric timestamp in float.
Example
In the following example code, we retrieve the creation time in timestamp format and then we use the datetime.fromtimestamp() to create a datatime object.
import datetime import os path = r"C:\Examples\samplefile.txt" create_time = os.path.getctime(path) print(create_time) create_date = datetime.datetime.fromtimestamp(create_time) print('Created on:', create_date)
Output
The output produced for the given example is as follows.
1652690657.7901006 Created on: 2022-05-16 14:14:17.790101
Using OS Module: File Modification Time On Windows
Here we find the last modified time of the file using the OS module. Initially, we need to import the OS module and datetime module. The OS module is used for getting the timestamp whereas the datetime module is used for creating a datetime object. We use the os.path.getmtime(‘path’) function to get the last modified time of that file. The os.path.getmtime(‘path’) returns the modification time in the numeric timestamp. Then we convert this timestamp to datetime object using the datetime.fromtimestamp() function.
Example
import datetime import os path = r"C:\Examples\samplefile.txt" modify_time = os.path.getmtime(path) print(modify_time) modify_date = datetime.datetime.fromtimestamp(modify_time) print('Modified on:', modify_date)
Output
1652690891.8609138 Modified on: 2022-05-16 14:18:11.860914
Using OS Module: File Modification Time On MAC AND UNIX
Here we find the last modified time of the file using the OS module. Initially, we need to import the OS module and datetime module. The OS module is used for getting the timestamp whereas the datetime module is used for creating a datetime object. We use the os.path.getmtime(‘path’) function to get the last modified time of that file. The os.path.getmtime(‘path’) returns the modification time in the numeric timestamp. Then we convert this timestamp to datetime object using the datetime.fromtimestamp() function.
Example
import datetime import os path = r"C:\Examples\samplefile.txt" modify_time = os.path.getmtime(path) print(modify_time) modify_date = datetime.datetime.fromtimestamp(modify_time) print('Modified on:', modify_date)
Output
1652690891.8609138 Modified on: 2022-05-16 14:18:11.860914
Using OS Module: File Modification Time On MAC AND UNIX
Here get the file creation time on Mac and Unix systems by using the OS and datetime module. The OS module is used for getting the timestamp whereas the datetime module is used for creating a datetime object. We use the st_birthtime attribute from the os.stat() function to get the creation time of the file. This returns a numeric timestamp, which is converted into a datetime object by using the datetime.fromtimestamp() function. .
Example
In this example, we will understand how to get the timestamp of file creation on MAC and UNIX systems.
import os import datetime path = r"C:\Examples\samplefile.txt" stat = os.stat(path) create_timestamp = stat.st_birthtime print(create_timestamp) create_time = datetime.datetime.fromtimestamp(create_timestamp) print(create_time)
Output
The output obtained from the above program is as follows.
1652690657.7901006 Created on: 2022-05-16 14:14:17.790101
Using Pathlib Module: File Creation Time On Windows
Here we use the pathlib module to get the creation time of a file. We initially import the pathlib and datetime modules. The pathlib module is used for getting the timestamp whereas the datetime module is used for creating a datetime object.
The pathlib.Path() is used to create a path of the file and returns the file path object. We use the st_ctime attribute from the stat() method to get the creation time of the file. This returns a numeric timestamp, which is converted into a datetime object by using the datetime.fromtimestamp() function.
Example
To get the timestamp of file creation on windows OS, the following program can be utilized.
import datetime import pathlib filename = pathlib.Path(r'C:\Examples\samplefile.txt') create_timestamp = filename.stat().st_ctime print(create_timestamp) create_time = datetime.datetime.fromtimestamp(create_timestamp) print(create_time)
Output
The output produced when the above program, is executed is as follows..
1652690657.7901006 2022-05-16 14:14:17.790101
Using Pathlib Module: File Modification Time On Windows
Here we find the last modified time of the file using the pathlib module. Initially, we need to import the pathlib module and datetime module. The pathlib module is used for getting the timestamp whereas the datetime module is used for creating a datetime object.
We use the st_mtime attribute from the stat() method is used to get the last modified time of the file. This returns a numeric timestamp, which is converted into a datetime object by using the datetime.fromtimestamp() function.
Example
In this example, we will get the file modification time on a system.
import datetime import pathlib filename = pathlib.Path(r'C:\Examples\samplefile.txt') modify_timestamp = filename.stat().st_mtime print(modify_timestamp) modify_date = datetime.datetime.fromtimestamp(modify_timestamp) print('Modified on:', modify_date)
Output
The output produced is shown.
1652690891.8609138 Modified on: 2022-05-16 14:18:11.860914
Получение даты создания и изменения файла в 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 .
Get file creation & modification date time
The getctime() function return the metadata change time of a file, reported by os.stat().
import os import datetime file = "example.txt" print("Created") print(os.path.getctime(file)) print(datetime.datetime.fromtimestamp(os.path.getctime(file))) print() print("Modified") print(os.path.getmtime(file)) print(datetime.datetime.fromtimestamp(os.path.getmtime(file)))
Sample output of above program.
Created 1547882934.5687482 2019-01-19 12:58:54.568748 Modified 1550935449.3555896 2019-02-23 20:54:09.355590
2019-02-25T08:09:44+05:30 2019-02-25T08:09:44+05:30 Amit Arora Amit Arora Python Programming Tutorial Python Practical Solution