Python – Get timestamp of an FTP file and compare with a local file

How do I reconcile the data from an FTP server with my local files?

  1. Necessary libraries
  2. Read remote file
  3. Read local file
  4. Compare timestamps
  5. Conclusion

In the code of my backup script, I had to synchronize the files from the FTP server with the files on the local system and, if necessary, download the file from the server.

In the following, I would like to explain the steps to you in more detail, so that you not only copy and paste them into your scripts, but that you also understand them.

Necessary libraries

We will not be able to do these tasks without libraries, so here’s the list of libraries needed:

  • os
    This module provides a portable way of using operating system dependent functionality.
  • ftplib
    You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers.
  • time
    This module provides various time-related functions.

Read remote file

I set up an FTP connection with the ftplib library in advance and saved this connection under the variable ftp_obj.

I declared and defined the path to the file on the server as remoteFile. In the following I will read out the datetime of the file and convert it into a timestamp:

remote_datetime = ftp_obj.voidcmd("MDTM " + remoteFile)[4:].strip() remote_timestamp = time.mktime(time.strptime(remote_datetime, '%Y%m%d%H%M%S'))

The DATETIME type is used when you need values that contain both date and time information. The supported range is’1000-01-01 00:00:00′ to ‘9999-12-31 23:59:59’.

The TIMESTAMP data type has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.

MySQL Documentation – 11.3.1 The DATE, DATETIME, and TIMESTAMP Types

Read local file

I saved the path to the local file as localFile and retrieve the timestamp of the last change to the file :

local_timestamp = os.path.getmtime(localFile)

This is also stored in a variable, so that we can make a comparison of the data afterwards.

Compare timestamps

The higher the date, the higher the timestamp. That’s why we need to get the variables we got into integer and then we can determine if the local file is newer or not.

if int(remote_timestamp) > int(local_timestamp):
    # remote file newer
    # remote file noit newer


This is the method I use to read remote timestamps. If you have an better idea and want to share it with me, I would ask you to contact me and tell me your ideas. That would be great!


ftp Program python technology Tips

Beitrag teilen

WhatsApp it

Folgen Sie uns