22

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
  • 112,593
  • 23
  • 157
  • 280
k_shil
  • 2,028
  • 1
  • 19
  • 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

40

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
  • 963,270
  • 265
  • 3,804
  • 3,187