find the last modified date of a file in python

To find the last modified date of a file in Python, we can make use of the os module with the os.path.getmtime() function which returns the timestamp of the last modification of the file in seconds since the epoch (January 1, 1970, 00:00:00 UTC).

We can then convert the timestamp into a human-readable format using the datetime module.

Here's the code:

main.py
import os
import datetime

file_path = "/path/to/your/file.ext"

# get the timestamp of the last modification of the file
timestamp = os.path.getmtime(file_path)

# convert the timestamp into a datetime object
last_modified_date = datetime.datetime.fromtimestamp(timestamp)

# print the last modified date in the desired format
print("Last modified date of the file is:", last_modified_date.strftime("%Y-%m-%d %H:%M:%S"))
422 chars
14 lines

In the code above, replace the file_path variable with the actual path of the file whose last modified date you want to find.

The strftime("%Y-%m-%d %H:%M:%S") method is used to format the last_modified_date into a string in the format "YYYY-mm-dd HH:MM:SS". You can modify the format string to get the desired output format.

gistlibby LogSnag