How to Get File Creation and Modification Date/Times

How do I get file creation and modification date/times?

In Python 3.4 and above, 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.

>>> import pathlib
>>> fname = pathlib.Path('test.py')
>>> assert fname.exists(), f'No such file: {fname}' # check that the file exists
>>> print(fname.stat())
os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)

For more information about what os.stat_result contains, refer to the documentation. For the modification time you want fname.stat().st_mtime:

>>> import datetime
>>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime, tz=datetime.timezone.utc)
>>> print(mtime)
datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)

If you want the creation time on Windows, or the most recent metadata change on Unix, you would use fname.stat().st_ctime:

>>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime, tz=datetime.timezone.utc)
>>> print(ctime)
datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)

This article has more helpful info and examples for the pathlib module.

Get file size, creation date and modification date in Python

https://docs.python.org/2.7/library/os.path.html#module-os.path

os.path.getsize(path) # size in bytes
os.path.ctime(path) # time of last metadata change; it's a bit OS specific.

Here's a rewrite of your program. I did this:

  1. Reformatted with autopep8 for better readability. (That's something you can install to prettify your code your code. But IDEs such as PyCharm Community Edition can help you to do the same, in addition to helping you with code completion and a GUI debugger.)
  2. Made your getListofFiles() return a list of tuples. There are three elements in each one; the filename, the size, and the timestamp of the file, which appears to be what's known as an epoch time (time in seconds since 1970; you will have to go through python documentation on dates and times).
  3. The tuples is written to your text file in a .csv style format (but note there are modules to do the same in a much better way).

Rewritten code:

import os

def getListOfFiles(ruta):
listOfFile = os.listdir(ruta)
allFiles = list()
for entry in listOfFile:
fullPath = os.path.join(ruta, entry)
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
else:
print('getting size of fullPath: ' + fullPath)
size = os.path.getsize(fullPath)
ctime = os.path.getctime(fullPath)
item = (fullPath, size, ctime)
allFiles.append(item)
return allFiles

ruta = "FolderPath"
miArchivo = open("TxtPath", "w")
listOfFiles = getListOfFiles(ruta)
for elem in listOfFiles:
miArchivo.write("%s,%s,%s\n" % (elem[0], elem[1], elem[2]))
miArchivo.close()

Now it does this.

my-MBP:verynew macbookuser$ python verynew.py; cat TxtPath
getting size of fullPath: FolderPath/dir2/file2
getting size of fullPath: FolderPath/dir2/file1
getting size of fullPath: FolderPath/dir1/file1
FolderPath/dir2/file2,3,1583242888.4
FolderPath/dir2/file1,1,1583242490.17
FolderPath/dir1/file1,1,1583242490.17
my-MBP:verynew macbookuser$

How to get File Created Date and Modified Date

You could use below code:

DateTime creation = File.GetCreationTime(@"C:\test.txt");
DateTime modification = File.GetLastWriteTime(@"C:\test.txt");

Get file modification date?

You could use exception handling; no need to first test if the file is there, just catch the exception if it is not:

try:
mtime = os.path.getmtime(file_name)
except OSError:
mtime = 0
last_modified_date = datetime.fromtimestamp(mtime)

This is asking for forgiveness rather than permission.

How do I get the modified date/time of a file in Python?

os.path.getmtime(filepath)

or

os.stat(filepath).st_mtime

OSX - How to get the creation & modification time of a file from the command line

stat reports the standard Unix dates, last access time, last modification time, and inode change time (which is often mistaken for creation time). Mac OS X also maintains the file creation time, and it's accessible using the GetFileInfo command:

$ GetFileInfo -d .bash_profile
10/08/2015 09:26:35

Here's a more complete example:

$ ls -l my_file.py
ls: my_file.py: No such file or directory
$ touch my_file.py
$ stat -x my_file.py
File: "my_file.py"
Size: 0 FileType: Regular File
Mode: (0644/-rw-r--r--) Uid: ( 501/ blm) Gid: ( 20/ staff)
Device: 1,5 Inode: 26863832 Links: 1
Access: Sun Dec 6 13:47:24 2015
Modify: Sun Dec 6 13:47:24 2015
Change: Sun Dec 6 13:47:24 2015
$ GetFileInfo my_file.py
file: "/Users/blm/my_file.py"
type: "\0\0\0\0"
creator: "\0\0\0\0"
attributes: avbstclinmedz
created: 12/06/2015 13:47:24
modified: 12/06/2015 13:47:24
$ echo hello >my_file.py
$ stat -x my_file.py
File: "my_file.py"
Size: 6 FileType: Regular File
Mode: (0644/-rw-r--r--) Uid: ( 501/ blm) Gid: ( 20/ staff)
Device: 1,5 Inode: 26863832 Links: 1
Access: Sun Dec 6 13:47:24 2015
Modify: Sun Dec 6 13:47:35 2015
Change: Sun Dec 6 13:47:35 2015
$ GetFileInfo my_file.py
file: "/Users/blm/my_file.py"
type: "\0\0\0\0"
creator: "\0\0\0\0"
attributes: avbstclinmedz
created: 12/06/2015 13:47:24
modified: 12/06/2015 13:47:35
$ cat my_file.py
hello
$ stat -x my_file.py
File: "my_file.py"
Size: 6 FileType: Regular File
Mode: (0644/-rw-r--r--) Uid: ( 501/ blm) Gid: ( 20/ staff)
Device: 1,5 Inode: 26863832 Links: 1
Access: Sun Dec 6 13:47:54 2015
Modify: Sun Dec 6 13:47:35 2015
Change: Sun Dec 6 13:47:35 2015
$ GetFileInfo my_file.py
file: "/Users/blm/my_file.py"
type: "\0\0\0\0"
creator: "\0\0\0\0"
attributes: avbstclinmedz
created: 12/06/2015 13:47:24
modified: 12/06/2015 13:47:35

Note that using vim to test this may be misleading because vim will write your modified file to a new temporary file, then rename the old one and the new one, so the creation time will be updated to when the file was written. See this post for a workaround I came up with for that.

How do you get a directory listing sorted by creation date in python?

Update: to sort dirpath's entries by modification date in Python 3:

import os
from pathlib import Path

paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)

(put @Pygirl's answer here for greater visibility)

If you already have a list of filenames files, then to sort it inplace by creation time on Windows (make sure that list contains absolute path):

files.sort(key=os.path.getctime)

The list of files you could get, for example, using glob as shown in @Jay's answer.


old answer
Here's a more verbose version of @Greg Hewgill's answer. It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on Windows).

#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time

# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'

# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)

# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
for stat, path in entries if S_ISREG(stat[ST_MODE]))
#NOTE: on Windows `ST_CTIME` is a creation date
# but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date

for cdate, path in sorted(entries):
print time.ctime(cdate), os.path.basename(path)

Example:

$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py


Related Topics



Leave a reply



Submit