14

I am trying to get the last modification date and time of a directory. while doing that I want to include the last modified date of the sub directories as well.

I could find some topics related to this question.(How to get file creation & modification date/times in Python?) but all of those just gives the last modified time of the root directory without considering the sub directories.

import os.path, time
print "last modified: %s" % time.ctime(os.path.getmtime(file))
print "created: %s" % time.ctime(os.path.getctime(file))

These lines of code just gives the last modified time of the root directory without considering the sub directories. Please help me on this.

Community
  • 1
  • 1
user4k
  • 191
  • 1
  • 2
  • 11
  • What do you mean by "include"? Do you want a `list` of times, one per subdirectory? Or do you want the most recent mod time of a directory hierarchy? – Robᵩ Apr 16 '15 at 20:16
  • Oh sorry for the confusion, I want the most recent mod time of a directory hierarchy? – user4k Apr 16 '15 at 20:17
  • 2
    Then you should walk that directory hierarchy (see `os.walk()`), collecting mod times as you go. Select the most recent one with `max()`. I'll create an example if you need it. – Robᵩ Apr 16 '15 at 20:18
  • thanks for the idea, if you give me an example that would be great. – user4k Apr 16 '15 at 20:19

1 Answers1

25

This should do what you ask:

import os
import time

print time.ctime(max(os.stat(root).st_mtime for root,_,_ in os.walk('/tmp/x')))

But I see you use os.path.getmtime(). So you are probably looking for this:

print time.ctime(max(os.path.getmtime(root) for root,_,_ in os.walk('/tmp/x')))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Doesn't linux do this book-keeping? I thought a directory's modification time was updates with its children. – user48956 Jun 15 '17 at 22:42
  • 4
    No, a directory's mod time only reflects modifications to the directory file (i.e. additions and deletions of entries). So /tmp/x is updated when /tmp/x/foo.txt is created, but not when /tmp/x/y/foo.txt is. (And, of course, /tmp/x is also not updated when /tmp/x/foo.txt is merely modified.) – Robᵩ Jun 16 '17 at 03:40
  • Is this only for Linux or would this work on other OS's? – Hofbr Oct 15 '20 at 13:46
  • While the original post only asked about subdirectories, I think its possible the OP may have also been interested in the age of files within the directory. I just want to point out that this answer does not consider file modification times. – Jed May 19 '23 at 18:39