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.
We will not be able to do these tasks without libraries, so here’s the list of libraries needed:
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.
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 else: # 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!