Get a files ‘last modified’ datetime using Python

Recently I wrote a script which checks an FTP server every morning for a new file. When it finds the remote file it must decide whether or not it is newer than the same file it downloaded at an earlier date. This is how the code compares the ‘last modified’ date of two files.

The ‘newest’ of two files will have the highest ‘last modified’ time.

Using os.path to find a file modified time

os.path.getmtime() returns a time stamp.
To turn it into a readable date you can use datetime.datetime.fromtimestamp().

¬†Get the ‘last modified’ time of a file on an FTP server

I’ve always used ftplib for handling FTP in my scripts. Over FTP, the command for getting a files modified time is MDTM. We can send this in Python using the code below.

The modifiedTime comes back with “213 ” at the start, this means the command was successful. The rest of the data is year + month + day + hour + minute + seconds or “%Y%m%d%H%M%S”. Using datetime we can make MDTM more readable.

ftplib.FTP and os.path are both great. Python wins!

8 thoughts on “Get a files ‘last modified’ datetime using Python

  1. Ken

    Thanks for this….BUT can you offer code to reconcile the unix with something like this…. 2012-09-11 20:40:08.320887….from

  2. Lindsay

    This works but it relies on the computers time being correct and of the same time zone, any way to fix this? Or at least check if both computers share the same time.

  3. Ben

    I’m struggling to write a script that does the same thing – any chance yours is uploaded somewhere for perusal?

  4. Chuck

    The second block of code doesn’t work on Python 3.0 +

    Line 7 should look like this print (datetime.fromtimestamp(modifiedTime).strftime(“%d%b%y %H:%M:%S”))

    It appears as though it needs the parentheses in order to work in version 3.0

    Correct me if I’m wrong.

  5. jes

    Hi Alex, thaks for the post!!

    I’m trying to check and download, if the fpt site has a new files added. Can we do it with ftplib?


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">