Python os.path.getmtime() Method



The Python os.path.getmtime() method is used to retrieve the last modification time of a file or directory.

The method returns a floating-point number representing the time of the most recent modification to the specified path, measured in seconds since the epoch (January 1, 1970, 00:00:00 UTC).

If the specified path does not exist or if there are permission issues preventing access to the path, the method raises a FileNotFoundError or PermissionError, respectively.

Syntax

Following is the basic syntax of the Python os.path.getmtime() method −

os.path.getmtime(path)

Parameter

This method accepts a string as a parameter representing the path to the file whose last modification time you want to retrieve.

Return Value

The method returns a floating-point number representing the number of seconds since the epoch (January 1, 1970) when the file was last modified.

Example

In the following example, we are retrieving the time of last modification of the file located at the given path "file_Path" and print it in seconds since the epoch −

import os
file_path = "/home/lenovo/documents/file.txt"
mtime = os.path.getmtime(file_path)
print("The file was modified at:",mtime)

Output

The output obtained is as follows −

The file was accessed at: 1640227200.0

Example

Here, we are retrieving the time of last modification of the current directory and print it in seconds since the epoch −

import os
current_dir = os.getcwd()
mtime = os.path.getmtime(current_dir)
print("The directory was modified at:",mtime) 

Output

Following is the output of the above code −

The directory was modified at: 1713938293.186791

Example

This example retrieves the time of last modification of the file located on a Windows system using the getmtime() method in human-readable format −

import os
import time
file_path = "C:\\Users\\Lenovo\\Downloads\\sql.txt"
mtime = os.path.getmtime(file_path)
print(time.ctime(mtime))

Output

We get the output as shown below −

Thu Sep 14 17:26:04 2023

Example

If we attempt to retrieve the time of last modification of a non-existent file path, the getmtime() method raises the "FileNotFoundError" −

import os
link_path = "/non/existent/path"
mtime = os.path.getmtime(link_path)
print("The path was modified at:",mtime)      

Output

The result produced is as shown below −

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    mtime = os.path.getmtime(link_path)
  File "<frozen genericpath>", line 67, in getmtime
FileNotFoundError: [WinError 3] The system cannot find the path specified: '/non/existent/path'
os_path_methods.htm
Advertisements