'How to get last modified time from pysftp

I am using pysftp to access files on SFTP. But I want to get the last modified date of these files and store it in mongo. This is to access the date again next time I run the code. I cannot find a function that returns me the date of the file.

class My_Connection(pysftp.Connection):
    def __init__(self, *args, **kwargs):
        try:
            if kwargs.get('cnopts') is None:
                kwargs['cnopts'] = pysftp.CnOpts()
        except pysftp.HostKeysException as e:
            self._init_error = True
            raise paramiko.ssh_exception.SSHException(str(e))
        else:
            self._init_error = False

        self._sftp_live = False
        self._transport = None
        super().__init__(*args, **kwargs)

    def __del__(self):
        if not self._init_error:
            self.close()

This is my connection class.

How can I get the date of the file that I am accessing.

Thanks.



Solution 1:[1]

If you want to retrieve a timestamp of a single specific file, use Connection.stat. It returns SFTPAttributes instance, which has st_mtime field with Unix time.

mtime = sftp.stat(remote_path).st_mtime

But if you need to retrieve timestamps of all files in a folder, calling Connection.stat for each would be ineffective. You already have the timestamps in the directory listing. The Connection.listdir_attr returns SFTPAttributes of all files in a directory.

See also How to sync only the changed files from the remote directory using pysftp?


You better use Paramiko though: pysftp vs. Paramiko.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1