Python: Get last modified information of a file
38. File Last Modified Info
Write a Python program to get the last modified information of a file.
Sample Solution:
Python Code:
Output:
2017-04-19 15:15:52
Explanation:
In the exercise above,
- This code imports the modules "os" and "time".
- It defines a function named "last_modified_fileinfo()" which retrieves the last modified date and time of a file specified by 'filepath'.
- Inside the "last_modified_fileinfo()" function:
- It gets the file status using the "os.stat()" function, which returns a tuple containing several pieces of information about the file, including the last modified time.
- It converts the last modified time to local time using "time.localtime()".
- It extracts the year, month, day, hour, minute, and second from the obtained date.
- It formats the date and time into a string in the format "YYYY-MM-DD HH:MM:SS".
- It prints the last modified date and time of the file 'test.txt' by calling the "last_modified_fileinfo()" function.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to fetch and display the last modified timestamp of a specified file in a human-readable format.
- Write a Python script to get the last modified date of a file and then calculate how many days ago it was modified.
- Write a Python program to obtain the file modification time and then compare it with the current time to compute the file’s age in hours.
- Write a Python function to retrieve a file's last modified time and then format it into "YYYY-MM-DD HH:MM:SS" using the os module.
Python Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Python program to convert two date difference in days, hours, minutes, seconds.
Next: Write a Python program to calculate an age in year.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics