Making a backup file + appending date time + movin

2019-06-14 10:11发布

问题:

I have a few of the pieces of this working but I'm struggling with putting them together.

I would like to take a file, move it to a backup folder, get the date time from that file, and append it to the file's name / change the file's name to file name + date time.

This part gets the date time in the format I want it. (print line is the date time formatted properly, but I don't need to print this line)

    Filepath = "C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt"
    modifiedTime = os.path.getmtime(Filepath) 
    firstFile = os.path.getmtime(Filepath)

    print (datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S"))

This part will rename / move the file (But it's missing the datetime)

    prevName = 'c:\\syncwork\\ace\\files\\ESAL_P\\ESAL_P.txt'
    newName = 'c:\\syncwork\\ace\\files\\ESAL_P\\Backup\\ESAL_P.txt'

    os.rename(prevName, newName)

How do I turn the print line with the formatting that I like into a string and append it to the end of the newName line?

AFTER my question was answered My final code looked like this:

Filepath = "C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt"
modifiedTime = os.path.getmtime(Filepath) 



timestamp = datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%Y_%H.%M.%S")

prevName = 'c:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt'
newName = 'c:\\SyncWork\\ACE\\Files\\ESAL_P\\Backup\\ESAL_P' 

os.rename(prevName, newName+"_"+timestamp + ".txt")
print(newName)  

回答1:

I just tested the following on a file named "temp" which was changed to "temp_Sep-15-14-08:42:57"

FilePath = 'temp' # replace the temp with your file path/name
modifiedTime = os.path.getmtime(FilePath) 

timeStamp =  datetime.datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S")
os.rename(FilePath,FilePath+"_"+timeStamp)


回答2:

This should do it:

timestamp = (datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S"))
newName = 'c:\\syncwork\\ace\\files\\ESAL_P\\Backup\\ESAL_P.txt.' + timestamp