Get File Timestamp in Python: os.stat, os.path.getmtime

Modified: | Tags: Python, Date and time

In Python, you can use the os and pathlib modules from the standard library to get file timestamp information, such as the creation, modification, and access time. It is provided in Unix time (Epoch time, Posix time) but can be converted to a datetime object.

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 (on Unix) / Creation time (on Windows)
  • birthtime: Creation time (on some Unix systems in the FreeBSD family, including macOS)

The sample code in this article was executed on macOS.

See the following article for basic usage of the pathlib module.

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')
source: os_stat.py

Get file timestamp with the os.stat_result object

You can get file metadata, such as timestamp information, as attributes of the os.stat_result object.

You can obtain the os.stat_result object with Path.stat() or os.stat().

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()))
# <class 'os.stat_result'>
source: os_stat.py

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.

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')))
# <class 'os.stat_result'>

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)))
# <class 'os.stat_result'>
source: os_stat.py

All these methods give you the same os.stat_result object.

print(p.stat() == os.stat('data/temp/test.txt') == os.stat(p))
# True
source: os_stat.py

Attributes of os.stat_result

You can get timestamps with the st_atime, st_mtime, and st_ctime attributes 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
source: os_stat.py

All attributes are floating-point numbers representing Unix time (Epoch time, Posix time). The conversion of this value to a datetime object will be described later.

print(type(st.st_ctime))
# <class 'float'>
source: os_stat.py

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))
# <class 'int'>
source: os_stat.py

While st_xxx is a floating-point number and st_xxx_ns is in nanoseconds, as noted in the official documentation, their accuracy isn't guaranteed.

Note: 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.11.4 documentation

os.stat_result has various other attributes, such as st_size, which indicates the file size in bytes. See the following article on getting the size of files and folders.

Get file timestamp 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
source: os_stat.py

You can also specify a pathlib.Path object as an argument instead of a path string.

print(os.path.getctime(p))
# 1549094615.9723485
source: os_stat.py

As shown in the source code, these functions retrieve the corresponding attributes from 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

The values obtained from these functions match those from the os.stat_result object.

print(os.path.getctime(p) == p.stat().st_ctime)
# True
source: os_stat.py

There are no functions provided to retrieve st_atime_ns, st_ctime_ns, st_mtime_ns, and st_birthtime.

Convert timestamp to the datetime object

As demonstrated earlier, timestamps from os.stat_result and similar sources are provided 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))
# <class 'datetime.datetime'>
source: os_stat.py

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, including 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
source: os_stat.py

Timestamp types: 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 (on Unix) / Creation time (on Windows)
  • birthtime: Creation time (on some Unix systems in the FreeBSD family, including macOS)

See the following page for details.

Get the modification time

You can retrieve the modification time, denoted as mtime, on any 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
source: os_stat.py

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
source: os_stat.py

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 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 targets Windows or macOS, you can use st_ctime or st_birthtime, respectively. However, for cross-platform support, you should define a function.

The sample code below is quoted from 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
source: os_stat.py

First, the code checks if the system is Windows using platform.system(). Then, based on the existence of the st_birthtime attribute, it employs exception handling to switch the operation.

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.

print(creation_date(p))
# 1549094605.9650702

print(datetime.datetime.fromtimestamp(creation_date(p)))
# 2019-02-02 17:03:25.965070
source: os_stat.py

Note that if st_birthtime does not exist, the function in this sample code returns st_mtime, which indicates the modification time. In some cases, it may be better to return None to indicate clearly that the creation time cannot be retrieved.

Related Categories

Related Articles