How to Get File Creation and Modification Dates Times in Python
Created
Modified
Using os.path Function
The os.path.getmtime()
function returns the time of last modification of path.
The os.path.getctime()
function returns the system’s ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path.
Here is an example code:
#!/usr/bin/python3
# Import module
import os.path, time
f = "file.txt"
print(time.ctime(os.path.getatime(f)))
print(time.ctime(os.path.getmtime(f)))
print(time.ctime(os.path.getctime(f)))
Sat May 7 17:33:53 2022 Sat May 7 17:33:53 2022 Sun May 8 09:27:51 2022
Using os.stat Function
Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. p
You can use os.stat() function, it really simple. For example,
#!/usr/bin/python3
# Import module
import os, time
f = "file.txt"
stat = os.stat(f)
print(time.ctime(stat.st_atime))
print(time.ctime(stat.st_mtime))
print(time.ctime(stat.st_ctime))
Sat May 7 17:33:53 2022 Sat May 7 17:33:53 2022 Sun May 8 09:27:51 2022
Using pathlib Module
you can use the object oriented pathlib module interface which includes wrappers for much of the os module. Here is an example of getting the file stats.
#!/usr/bin/python3
# Import module
import pathlib, time
f = "file.txt"
p = pathlib.Path(f)
stat = p.stat()
print(time.ctime(stat.st_atime))
print(time.ctime(stat.st_mtime))
print(time.ctime(stat.st_ctime))
Sat May 7 17:33:53 2022 Sat May 7 17:33:53 2022 Sun May 8 09:27:51 2022
Python Errors
FileNotFoundError:
f = "file.tx"
# ...
stat = p.stat()
return self._accessor.stat(self, follow_symlinks=follow_symlinks) FileNotFoundError: [Errno 2] No such file or directory: 'file.tx'