shutil.copy2()
is perfectly capable of copying the metadata containing the date and time of the last modification of the file:
Identical to copy()
except that copy2()
also attempts to preserve all
file metadata.
copy2()
uses copystat()
to copy the file metadata. Please see
copystat()
for more information about platform support for modifying
symbolic link metadata.
Follows a code that ensures that the source will be copied to the destination together with all possible metadata. If the destination has a creation date older than the source, the destination will be overwritten with the source:
import shutil
import os
def sincronizar( src, dst ):
# Verifica se origem existe
if not os.path.exists( src ):
return -1; # Erro
# Copia se o arquivo de destino
# nao existir
if not os.path.exists( dst ):
shutil.copy2( src, dst )
return 1; # Sucesso
# Recupera metadados da origem e do destino
dst_info = os.stat(dst)
src_info = os.stat(src)
# Copia somente se a data de modificao do arquivo
# de destino estiver mais antiga que 1 segundo
if( src_info.st_mtime - dst_info.st_mtime > 1 ):
shutil.copy2( src, dst )
return 1 # Sucesso
return 0 # Sucesso (sem copia)