2

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?

Anubhav Singh
  • 8,321
  • 4
  • 25
  • 43
Pedro Alves
  • 1,004
  • 1
  • 21
  • 47
  • Possible duplicate of [How to get file creation & modification date/times in Python?](https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python) – jose_bacoy Jun 18 '19 at 15:00

2 Answers2

1

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
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
0

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)
olinox14
  • 6,177
  • 2
  • 22
  • 39