Assuming the file exists (using os.path.exists(filename) to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.
Asked
Active
Viewed 7.7k times
66
Bill the Lizard
- 386,424
- 207
- 554
- 861
3 Answers
133
>>> import os
>>> f = os.path.getmtime('test1.jpg')
>>> f
1223995325.0
since the beginning of (epoch)
Jack
- 19,841
- 11
- 47
- 47
-
1Thanks, this was helpful. This seems to be the more direct approach to my specific question, but the os.stat solution gives more information. – Bill the Lizard Dec 17 '08 at 17:08
-
6I didn't know that there was an explicit function for this. Live and learn I guess. – Douglas Leeder Sep 04 '09 at 15:24
-
2Probably the more portable solution – djhaskin987 Sep 05 '14 at 20:32
-
thank you for this solution – WhyWhat May 11 '20 at 11:31
-
This is the best answer for the specific question asked. The more generic stats give more information and is preferable when that additional information is needed, but when it's not - like in the scenario asked about here - this extraneous information and the extra layers are just unneeded burden. – Tom Feb 15 '21 at 22:34
68
import os
filename = "/etc/fstab"
statbuf = os.stat(filename)
print("Modification time: {}".format(statbuf.st_mtime))
Linux does not record the creation time of a file (for most fileystems).
dowhilegeek
- 7
- 2
Douglas Leeder
- 50,599
- 9
- 90
- 136
-
Thank you. It appears that Linux doesn't store the file creation time. It seems like I should have known that. :) – Bill the Lizard Dec 17 '08 at 17:09
42
New for python 3.4+ (see: pathlib)
import pathlib
path = Path('some/path/to/file.ext')
last_modified = path.stat().st_mtime
Brian Bruggeman
- 4,536
- 2
- 32
- 49
-
It seems like `pathlib` is useful for getting a file when you have an absolute path and aren't sure about the OS. But if you can assume that the file in question is in the same directory as your script, then it seems like the other approaches may be easier. – Teepeemm May 08 '18 at 21:33
-
5
-
In that case, I don't see a difference between `pathlib.Path("file.ext").stat()` and `os.stat("file.ext")`. – Teepeemm May 09 '18 at 00:47
-
7pathlib is intended to provide an object oriented method for obtaining many of the features found in os and stat. It's not intended to replace but to live along side. Additionally, it becomes more handy when you need to pass around paths and you want access to file information or to open the file directly. – Brian Bruggeman May 09 '18 at 00:58
-
1