- Get file timestamps (creation, modification, access date and time) in Python
- Get os.stat_result with timestamp information
- Path.stat()
- os.stat()
- Attributes of os.stat_result
- Get timestamps with the os.path function
- Convert timestamp to datetime
- Type of timestamp: atime, ctime, mtime, birthtime
- Get the modification date and time
- Get the creation date and time
- Cross-platform approach
- Получение даты создания и изменения файла в Python
Get file timestamps (creation, modification, access date and time) in Python
In Python, you can use the standard library os and pathlib modules to get timestamps such as the creation, modification, and access date and times of files. It can be obtained in Unix time (Epoch time, Posix time) but can be converted to date and time using the datetime module.
You can get the following timestamps. The meaning differs depending on the OS, so be especially careful about the creation time.
- atime: Access time
- mtime: Modification time
- ctime: Change time (Unix) and creation time (Windows)
- birthtime: Creation time (Some Unix in the FreeBSD family, including macOS)
This article describes the following contents.
- Get os.stat_result with timestamp information
- Path.stat()
- os.stat()
- Attributes of os.stat_result
- Cross-platform approach
As an example, create a file and update it after 10 seconds.
import os import pathlib import datetime import time import platform p = pathlib.Path('data/temp/test.txt') p.write_text('test') time.sleep(10) p.write_text('update')
Get os.stat_result with timestamp information
You can get file metadata, such as timestamps, as attributes of the os.stat_result object.
Path.stat()
You can get the os.stat_result object with the stat() method of the pathlib.Path object.
print(p.stat()) # os.stat_result(st_mode=33188, st_ino=8728494137, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=6, st_atime=1549094615, st_mtime=1549094615, st_ctime=1549094615) print(type(p.stat())) #
os.stat()
You can also use the os.stat() function of the os module to get the os.stat_result object. The argument can be a path string or a pathlib.Path object (Python 3.6 or later).
print(os.stat('data/temp/test.txt')) # os.stat_result(st_mode=33188, st_ino=8728494137, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=6, st_atime=1549094615, st_mtime=1549094615, st_ctime=1549094615) print(type(os.stat('data/temp/test.txt'))) # print(os.stat(p)) # os.stat_result(st_mode=33188, st_ino=8728494137, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=6, st_atime=1549094615, st_mtime=1549094615, st_ctime=1549094615) print(type(os.stat(p))) #
All methods give you the same os.stat_result object.
print(p.stat() == os.stat('data/temp/test.txt') == os.stat(p)) # True
Attributes of os.stat_result
You can get timestamps with the attributes st_atime , st_mtime , and st_ctime of the os.stat_result object. On some Unix systems of FreeBSD family, including macOS, there is also an attribute st_birthtime . The meaning of each is described later.
st = p.stat() print(st.st_atime) # 1549094615.972488 print(st.st_mtime) # 1549094615.9723485 print(st.st_ctime) # 1549094615.9723485 print(st.st_birthtime) # 1549094605.9650702
All attributes are floating-point numbers and represent Unix time (Epoch time, Posix time). How to convert this value to datetime is described later.
There are also st_atime_ns , st_ctime_ns , and st_mtime_ns which store the value of an integer int in nanoseconds. There is no equivalent attribute for st_birthtime .
print(st.st_ctime_ns) # 1549094615972348510 print(type(st.st_ctime_ns)) #
Note that, as shown in the official documentation, floating point number float contains information after the decimal point, and xxx_ns stores values in nanoseconds, but the accuracy is not guaranteed.
The exact meaning and resolution of the st_atime , st_mtime , and st_ctime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details. os — Miscellaneous operating system interfaces — Python 3.10.0 documentation
os.stat_result has various other attributes, such as st_size , which indicates the size of the file in bytes. See the following article on getting the size of files and folders.
Get timestamps with the os.path function
You can also get timestamps with the os.path function, getatime() , getmtime() , and getctime() .
print(os.path.getatime('data/temp/test.txt')) # 1549094615.972488 print(os.path.getmtime('data/temp/test.txt')) # 1549094615.9723485 print(os.path.getctime('data/temp/test.txt')) # 1549094615.9723485
In Python 3.6 or later, you can also specify pathlib.Path object as an argument instead of a path string.
print(os.path.getctime(p)) # 1549094615.9723485
As you can see in the source code, these functions just get the corresponding attributes of os.stat_result .
def getmtime(filename): """Return the last modification time of a file, reported by os.stat().""" return os.stat(filename).st_mtime def getatime(filename): """Return the last access time of a file, reported by os.stat().""" return os.stat(filename).st_atime def getctime(filename): """Return the metadata change time of a file, reported by os.stat().""" return os.stat(filename).st_ctime
Of course, you can get exactly the same value as getting os.stat_result with Path.stat() or os.stat() and specifying its attribute.
print(os.path.getctime(p) == p.stat().st_ctime) # True
Functions to get st_atime_ns , st_ctime_ns , st_mtime_ns and st_birthtime are not provided.
Convert timestamp to datetime
As in the previous sample code, the timestamp is expressed in Unix time (Epoch time, Posix time).
To convert it to a datetime object, use the datetime.fromtimestamp() function of the datetime module.
dt = datetime.datetime.fromtimestamp(p.stat().st_ctime) print(dt) # 2019-02-02 17:03:35.972348 print(type(dt)) #
For more information, including how to specify the time zone when converting, see the following article.
The datetime object can be converted to a string in any format or ISO format.
print(dt.strftime('%Y年%m月%d日 %H:%M:%S')) # 2019年02月02日 17:03:35 print(dt.isoformat()) # 2019-02-02T17:03:35.972348
For more information, see the following articles.
Type of timestamp: atime, ctime, mtime, birthtime
As mentioned in the introduction, there are different types of timestamps: atime, ctime, mtime, and birthtime.
- atime: Access time
- mtime: Modification time
- ctime: Change time (Unix) and creation time (Windows)
- birthtime: Creation time (Some Unix in the FreeBSD family, including macOS)
See the following page for details.
Get the modification date and time
For the so-called modification time, you can get mtime regardless of the OS.
Use the st_mtime attribute of os.stat_result or the os.path.getmtime() function as in the sample code so far.
print(os.path.getmtime('data/temp/test.txt')) # 1549094615.9723485 print(p.stat().st_mtime) # 1549094615.9723485
To convert it to a datetime object, use the datetime.fromtimestamp() function of the datetime module.
print(datetime.datetime.fromtimestamp(p.stat().st_mtime)) # 2019-02-02 17:03:35.972348
On Unix, you can use ctime to get the last modified time of metadata, so if you want to detect file name changes, for example, use ctime instead of mtime. Note that on Windows, ctime is the creation time.
Get the creation date and time
As mentioned above, the method of getting the creation time varies depending on the OS.
- Windows: ctime
- Some Unix such as macOS: birthtime
- Other Unix: The creation time cannot be retrieved
Cross-platform approach
If your program is only for Windows or macOS, you can use st_ctime or st_birthtime , but if you want to support multiple platforms, you should define a function.
Cite the sample code listed in the following question and answer on Stack Overflow.
def creation_date(path_to_file): """ Try to get the date that a file was created, falling back to when it was last modified if that isn't possible. See http://stackoverflow.com/a/39501288/1709587 for explanation. """ if platform.system() == 'Windows': return os.path.getctime(path_to_file) else: stat = os.stat(path_to_file) try: return stat.st_birthtime except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return stat.st_mtime
First, it checks whether the system is Windows or not with platform.system() , and then it uses exception handling to switch the operation depending on whether the st_birthtime attribute exists or not.
See the following article for more information about platform.system() and exception handling.
The argument can be a path string or a pathlib.Path object (Python 3.6 or later).
print(creation_date(p)) # 1549094605.9650702 print(datetime.datetime.fromtimestamp(creation_date(p))) # 2019-02-02 17:03:25.965070
Note that the function in this sample code returns st_mtime , which indicates the modification time, if st_birthtime does not exist. In some cases, it may be better to return None to indicate clearly that the creation time cannot be retrieved.
Получение даты создания и изменения файла в 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 .