Python os.path.getmtime() Method

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

This method is helpful for file system operations where you need information about when a file was last modified. It can be helpful for tasks like syncing files, monitoring file changes, or in applications where file modification times are critical, such as backup or version control systems.

Syntax

os.path.getmtime(path)

Parameters

Name Description
path (string) It is the path of the file or directory.

Return value

It returns the last modification time in seconds since the epoch.

Example 1: Getting the last modification time of a file

Python os.path.getmtime() - Getting the last modification time of a file

import os
import time

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt'

modification_time = os.path.getmtime(path)

print("Last modification time:", time.ctime(modification_time))

Output

Last modification time: Sun Feb 4 22:01:03 2024

Here is the screenshot of the last modification time:

Screenshot of modified time in GUI

Example 2: Getting the last modification time of a file

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt'

try:
  modification_time = os.path.getmtime(path)
  print("Last modification time:", modification_time)
except FileNotFoundError:
  print("File not found.")

Output

Last modification time: 1707064263.4886367

That’s all!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.