23

I use the following code to get modification date of file if it exists:

if os.path.isfile(file_name):
    last_modified_date = datetime.fromtimestamp(os.path.getmtime(file_name))
else:
    last_modified_date = datetime.fromtimestamp(0)

Is there a more elegant/short way?

martineau
  • 119,623
  • 25
  • 170
  • 301
k_shil
  • 2,108
  • 1
  • 20
  • 25
  • 2
    I believe this answers your question. http://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python – D_G Dec 20 '14 at 14:07

1 Answers1

42

You could use exception handling; no need to first test if the file is there, just catch the exception if it is not:

try:
    mtime = os.path.getmtime(file_name)
except OSError:
    mtime = 0
last_modified_date = datetime.fromtimestamp(mtime)

This is asking for forgiveness rather than permission.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343