-1

I am trying to copy files from one folder to another. Sometimes the folder has 5 gigs worth of files, but I only need two months worth of files. How do I tell python to copy files from a date range of today to 2 months ago?

example: copy files created on 2.4.2022 - 4.4.2022.

would I do:

import shutil
import datetime

for file in range(2.4.2022, 4.4.2022):
    shutil.copy('C:\\folder', 'C:\\folder2')

I need python to automatically use today's date. So when the code is run Python will use the date range of, the date that the code is run to two months ago.

Thank you for your help!

I am not good with python yet. I was able to use shutil.copytree for one folder. That worked because I need all the files in that particular folder, as for the second folder I don't need all the files.

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • What do the filenames look like? Are they all in the same folder or hierarchical by date? – jarmod Apr 04 '22 at 15:12
  • see [How to get file creation and modification date/times](https://stackoverflow.com/q/237079/10197418): obtain the file's timestamp. convert it to datetime, and check if it is in your desired range; if so, copy. – FObersteiner Apr 05 '22 at 11:53
  • the filenames are .BAK files for MS Word. – Beyond Unknown Apr 07 '22 at 17:46

1 Answers1

0

I would recommend a couple of things.

First, you can compare dates as long as they have the right format, for example, you need to split your folder names from 2.4.2022, to datetime(2022,4,2), then in your program you can compare them like.

if datetime(2022,4,2) > datetime(2020,1,1):
    print ("This folder needs to be copied")
    ...your copy statements

So, if this is a one time activity, you can just convert those folder names to datetime(), then compare them in a for loop against the initial date that you need (or dates), then run the copy.

Marco
  • 1,172
  • 9
  • 24
  • That is a genius way of doing this! thank you. I have been trying to get this done, but I have reached a roadblock. this what i have so far, and it keeps giving me a permission error [errno 13] – Beyond Unknown Apr 07 '22 at 17:47
  • import shutil from datetime import datetime for files in os.listdir(C:\folder1): if datetime (2022,7,4) > datetime(2022,4,4): shutil.copy(C:\\folder1, C\\folder2\backup) – Beyond Unknown Apr 07 '22 at 17:56
  • If you get a permission error that is something different, can you manually do the copy? Also, this path is wrong -> `..., C\\folder2\backup` – Marco Apr 08 '22 at 00:53
  • Yes, that is what makes this strange. I can manually copy the files, I created a new folder with new files and I get the same error. I can't figure out what permission is blocking it. I am logged in as the local administrator, and I have full control permissions. I don't get it. – Beyond Unknown Apr 08 '22 at 13:42