Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file modification date? [duplicate]

Tags:

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?

like image 907
k_shil Avatar asked Dec 20 '14 14:12

k_shil


People also ask

Does copying a file change creation time?

Windows does not preserve the creation_time in the copied file of the original file. The modification time is copied. The creation time is always the current system time.

Can you change the date a file was modified?

Unfortunately, this isn't possible. You can view certain and change certain file attributes in File Explorer, but you can't change the last viewed, edited, or modified dates.

How do I copy a file without changing the date modified?

cp command provides an option –p for copying the file without changing the mode, ownership and timestamps. ownership, mode and timestamp. $ cp -p num.


1 Answers

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.

like image 189
Martijn Pieters Avatar answered Sep 20 '22 12:09

Martijn Pieters