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.
Step 1: Import the required modules
To work with files in Python, we need to import the os module. The os module provides various functions related to operating system tasks, including file operations.
import os
Step 2: Specify the file path
Next, you need to specify the path of the file for which you want to retrieve the last modified time. This can be the absolute path or the relative path from the current working directory.
file_path = 'path/to/your/file.txt'
Step 3: Use the os.path module to get the last modified time
The os.path module provides functions for manipulating pathnames. We can use the getmtime() function from this module to retrieve the last modified time of a file.
last_modified = os.path.getmtime(file_path)
This will return the last modified time as a floating-point number representing the number of seconds since the epoch (January 1, 1970).
Step 4: Convert the last modified time to a readable format (optional)
If you want to display the last modified time in a human-readable format, you can use the datetime module to convert it.
import datetime
last_modified_dt = datetime.datetime.fromtimestamp(last_modified)
Step 5: Display the last modified time
You can now print the last modified time either as a floating-point number or in a human-readable format.
print("Last Modified Time (float):", last_modified)
print("Last Modified Time (datetime):", last_modified_dt)
That's it! You have successfully retrieved the last modified time of a file in Python.
Full code example
Here's the complete code example that combines all the steps:
import os
import datetime
file_path = 'path/to/your/file.txt'
last_modified = os.path.getmtime(file_path)
last_modified_dt = datetime.datetime.fromtimestamp(last_modified)
print("Last Modified Time (float):", last_modified)
print("Last Modified Time (datetime):", last_modified_dt)
Make sure to replace 'path/to/your/file.txt' with the actual file path you want to retrieve the last modified time for.
I hope this tutorial helps! Let me know if you have any further questions.