Skip to content

Instantly share code, notes, and snippets.

@jbarham
Last active January 2, 2017 00:10
Show Gist options
  • Select an option

  • Save jbarham/3375913 to your computer and use it in GitHub Desktop.

Select an option

Save jbarham/3375913 to your computer and use it in GitHub Desktop.
Returns timestamp of most recently modified file under given path
#!/usr/bin/env python
import sys, os, time
def newest_mtime(path):
"""Returns timestamp of newest file under path."""
newest_time = 0
for root, dirs, files in os.walk(path):
for fname in files:
mtime = os.stat(os.path.join(root, fname)).st_mtime
if mtime > newest_time:
newest_time = mtime
return newest_time
def newest_timestamp(path, format="%Y%m%d%H%M"):
return time.strftime(format, time.localtime(newest_mtime(path)))
if __name__ == "__main__":
print(newest_timestamp(sys.argv[1]))
@jbarham

jbarham commented Dec 5, 2016 •

Copy link
Copy Markdown
Author

This script returns the timestamp of the file that has been changed most recently under the given directory path. It's useful to e.g. generate a URL timestamp for a website's static file root directory.

Use it in Django like so:

local_settings.py:

from newest_mtime import newest_timestamp
ts = newest_timestamp('./static/')
STATIC_URL = '/static/v%/' % ts

nginx.conf:

location ~ ^/static/v\d+/(.*)$ {
    alias /home/django/site/static/$1;
    expires max;
}

For more Django tips & tricks see my presentation at http://www.wombatsoftware.com/mpug2016.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment