Skip to main content

How to get the last modified time of a file in Python

How to get the last modified time of a file in Python.

Here's a step-by-step tutorial on how to get the last modified time of a file in Python:

  1. Import the necessary modules:
import os
import time

We need to import the os module to interact with the operating system and the time module to work with time-related functions.

  1. Get the file path:
file_path = 'path/to/your/file.txt'

Replace 'path/to/your/file.txt' with the actual path to the file you want to check.

  1. Check if the file exists:
if os.path.exists(file_path):

We use the os.path.exists() function to check if the file exists at the given path.

  1. Get the last modified time of the file:
    modified_time = os.path.getmtime(file_path)

The os.path.getmtime() function returns the last modified time of the file as a timestamp.

  1. Convert the timestamp to a readable format:
    modified_time_readable = time.ctime(modified_time)

We use the time.ctime() function to convert the timestamp to a readable format. This will give you a string representation of the modified time.

  1. Print the last modified time:
    print("Last modified time:", modified_time_readable)

This will print the last modified time of the file in a human-readable format.

Putting it all together, here's the complete code:

import os
import time

file_path = 'path/to/your/file.txt'

if os.path.exists(file_path):
modified_time = os.path.getmtime(file_path)
modified_time_readable = time.ctime(modified_time)
print("Last modified time:", modified_time_readable)
else:
print("File not found!")

Make sure to replace 'path/to/your/file.txt' with the actual path to your file.