Python | os.path.getmtime() method (original) (raw)
Last Updated : 15 Jun, 2026
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.
Python `
import os path = "sample.txt" t = os.path.getmtime(path) print(t)
`
**Output
1718275200.0
**Explanation: os.path.getmtime(path) returns the last modification time of the specified file as a floating-point value.
Syntax
os.path.getmtime(path)
- **Parameters: path - Path of the file or directory whose modification time is to be retrieved.
- **Return Value: Returns a floating-point number representing the last modification time in seconds since the epoch.
Examples
**Example 1: This example retrieves the modification time and converts it into a human-readable date and time format using the time module.
Python `
import os import time
path = "sample.txt" t = os.path.getmtime(path) print(time.ctime(t))
`
**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.
Python `
import os
f1 = "file1.txt" f2 = "file2.txt"
if os.path.getmtime(f1) > os.path.getmtime(f2): print(f1) else: print(f2)
`
**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.
Python `
import os path = "data.txt"
try: print(os.path.getmtime(path)) except OSError: print("File does not exist or cannot be accessed")
`
**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.