Get File Creation Time with Python on Linux

Get file creation time with Python on linux

You probably can't.:

3.1)  How do I find the creation time of a file?

You can't - it isn't stored anywhere. Files have a last-modified
time (shown by "ls -l"), a last-accessed time (shown by "ls -lu")
and an inode change time (shown by "ls -lc"). The latter is often
referred to as the "creation time" - even in some man pages -
but that's wrong; it's also set by such operations as mv, ln,
chmod, chown and chgrp.

The man page for "stat(2)" discusses this.

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$

With python, How to read the date created of a file?

You need to be using a string for the filename instead of the file object.

>>> import os.path, time
>>> f = open('test.test')
>>> data = f.read()
>>> f.close()
>>> print "last modified: %s" % time.ctime(os.path.getmtime('test.test'))
last modified: Fri Apr 13 20:39:21 2012
>>> print "created : %s" % time.ctime(os.path.getctime('test.test'))
created : Fri Apr 13 20:39:21 2012

Get file creation time with Python on Mac

Use the st_birthtime property on the result of a call to os.stat() (or fstat/lstat).

def get_creation_time(path):
return os.stat(path).st_birthtime

You can convert the integer result to a datetime object using datetime.datetime.fromtimestamp().

For some reason I don't think this worked on Mac OS X when this answer was first written, but I could be mistaken, and it does work now, even with older versions of Python. The old answer is below for posterity.


Using ctypes to access the system call stat64 (works with Python 2.5+):

from ctypes import *

class struct_timespec(Structure):
_fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]

class struct_stat64(Structure):
_fields_ = [
('st_dev', c_int32),
('st_mode', c_uint16),
('st_nlink', c_uint16),
('st_ino', c_uint64),
('st_uid', c_uint32),
('st_gid', c_uint32),
('st_rdev', c_int32),
('st_atimespec', struct_timespec),
('st_mtimespec', struct_timespec),
('st_ctimespec', struct_timespec),
('st_birthtimespec', struct_timespec),
('dont_care', c_uint64 * 8)
]

libc = CDLL('libc.dylib') # or /usr/lib/libc.dylib
stat64 = libc.stat64
stat64.argtypes = [c_char_p, POINTER(struct_stat64)]

def get_creation_time(path):
buf = struct_stat64()
rv = stat64(path, pointer(buf))
if rv != 0:
raise OSError("Couldn't stat file %r" % path)
return buf.st_birthtimespec.tv_sec

Using subprocess to call the stat utility:

import subprocess

def get_creation_time(path):
p = subprocess.Popen(['stat', '-f%B', path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.wait():
raise OSError(p.stderr.read().rstrip())
else:
return int(p.stdout.read())

display time according to the time zone the file was created

datetime.datetime.fromtimestamp(test_time_since_epoch).strftime("%d/%m/%Y, %H:%M:%S")

https://docs.python.org/2/library/datetime.html#datetime.date.fromtimestamp

Return the local date corresponding to the POSIX timestamp....

How do I get the time a file was last modified in Python?

os.stat()

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).



Related Topics



Leave a reply



Submit