Pedro Alves
Pedro Alves

Reputation: 1054

Python - It returns the modified date from the folder

I've the following code in order to get the last modified date from the files present in the Folder:

path = 'C://Reports//Script//'

modTimesinceEpoc = os.path.getmtime(path)
modificationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modTimesinceEpoc))
modificationTime = datetime.strptime(modificationTime, '%Y-%m-%d %H:%M:%S')

But this returns the modified date from the folder and I only want to check the modified dates from the files, since I don't want to know the modified date from the folder.

How can I update my code?

Upvotes: 2

Views: 1873

Answers (2)

Subhrajyoti Das
Subhrajyoti Das

Reputation: 2710

You need to list all the files in the directory and find timestamp after that. Below is a sample code.

Update - Added handling for Windows and Linux separately.

import os
import time
import platform
from datetime import datetime

path = 'C://Reports/Script/'
files_path = ['%s%s'%(path, x) for x in os.listdir(path)]

print platform.system()

for file_p in files_path:
    if platform.system() == 'Windows':
        modTimesinceEpoc = os.path.getctime(file_p)
    else:
        statbuf = os.stat(file_p)
        modTimesinceEpoc = statbuf.st_mtime

    modificationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modTimesinceEpoc))
    modificationTime = datetime.strptime(modificationTime, '%Y-%m-%d %H:%M:%S')

    print file_p, modificationTime

Upvotes: 1

olinox14
olinox14

Reputation: 6643

Using the path.py library, you could do:

from path import Path

mydir = Path(r"\path\to\dir")

mtime = max([f.getmtime() for f in mydir.walkfiles()])
print(mtime)

Or, if you can not use any external libraries:

import os
from pathlib import Path

mydir = Path(r"c:\dev\python\mncheck")

mtime = max([mydir.joinpath(root).joinpath(f).stat().st_mtime for root, _, files in os.walk(mydir) for f in files])

print(mtime)

Upvotes: 0

Related Questions