Finding the last modified date and time of a file in Python

So, guys today we will learn how to get or find the last modified date and time of a file in Python. Let’s do it together. We need to pass the file name on the bases of which it will provide us the required details. The name of the file that we are going to pass must be the same as that of the original file.

If there is a minor change in the name then it will give you an error. To avoid this make sure you give the same path or file name.

Also read: OS Module in Python

How to Find the last modified date and time of a file in Python

Here is the solution to your question. First of all, I would like to explain the code in detail so that you can understand it very well. Beginning with importing  “os.path, time ”  is used so that we can get the time of the last modification of the file. Then moving further is the normal print statement in which statements are written that we want to print on the screen after there some call getmtime and getctime, would like to explain that is nothing but,

  • getmtime – It gives us the time of last modification.
  • getctime – It gives us the time of the creation.

The time that it gives after running the code is in the format of  :

Weekday  Month  Date  Time (hrs: s: ms)  Year

I have taken the example of Project.docx  you are supposed to put up your file’s name.

Source code :

import os.path, time
print("Last modified: %s" % time.ctime(os.path.getmtime("Project.docx")))
print("Created: %s" % time.ctime(os.path.getctime("Project.docx")))

Output :

Last modified: Thu Apr 2 16:16:42 2020
Created: Fri Apr 3 14:03:04 2020

 

Want to learn more have a look!

COVID-19 Outbreak Prediction Using Machine Learning in Python

Time Conversion from 12-hour to 24-hour format in Python

Leave a Reply

Your email address will not be published. Required fields are marked *