![]() |
VOOZH | about |
os.path.getmtime() is used to get the last modification time of a file or directory. It returns the modification time as the number of seconds since the Unix epoch. This method is useful for checking when a file was last updated.
Example: The following example gets the last modification time of a file.
Output
1718275200.0
Explanation: os.path.getmtime(path) returns the last modification time of the specified file as a floating-point value.
os.path.getmtime(path)
Example 1: This example retrieves the modification time and converts it into a human-readable date and time format using the time module.
Output
Sat Jun 13 10:45:20 2026
Explanation: time.ctime(t) converts the timestamp returned by os.path.getmtime() into a readable date and time string.
Example 2: This example compares modification times of two files and identifies the most recently modified file.
Output
file2.txt
Explanation: os.path.getmtime() is used on both files and the file with the greater timestamp is the one modified more recently.
Example 3: This example safely checks the modification time and handles the case where the file does not exist.
Output
File does not exist or cannot be accessed
Explanation: If os.path.getmtime(path) cannot access the specified file, it raises an OSError, which is handled using try-except.