Get the Modified Time of a File using Python

To get the modified time of a file using Python:

import os.path
import time

# Specify the full file path
file_path = r"Path where the file is stored\file_name.file_extension"

# Get the modified time of the file
modified_time = os.path.getmtime(file_path)

# Convert the modified time to a readable format
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(modified_time))

print(formatted_time)

Example

Imagine that a text file called ‘New_Products‘ is stored under the following path:

C:\Users\Ron\Desktop\Test\New_Products.txt

Where the modified time of that file is:

New_Products   2024-04-26 19:26:41

To retrieve that time using Python:

import os.path
import time

# Specify the full file path
file_path = r"C:\Users\Ron\Desktop\Test\New_Products.txt"

# Get the modified time of the file
modified_time = os.path.getmtime(file_path)

# Convert the modified time to a readable format
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(modified_time))

print(formatted_time)

The result:

2024-04-26 19:26:41

Leave a Comment