0

I wanna deleted files in directory, but necessarily created in X date at Y date. I think used the library os but idk how to specify a date condition.

import os
import pandas as pd

path = 'directory'
dir = os.listdir(path)

for file in dir:
  if file ... in dir:
    os.remove(file)
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • 1
    Does this answer your question? [How do I get file creation and modification date/times?](https://stackoverflow.com/questions/237079/how-do-i-get-file-creation-and-modification-date-times) – Yevhen Kuzmovych Nov 04 '22 at 13:57

1 Answers1

0

You can get the last accessed time with os.path.getatime('/path/to/your/file'). Also, last modification time (os.path.getmtime) and creation time (os.path.getctime). More on those here. But these are in UNIX epoch format. So you should first convert the time you want to UNIX epoch format with the following command:

from datetime import datetime as dt

# Create the time you want
t = dt(2022, 11, 4, 18, 8, 30)

# Convert to UNIX epoch time
converted = t.timestamp()

# Output: 1667572710.0

Now you can check each file's modification/access/creation time and do the comparison, then delete ones you want

import os
from datetime import datetime as dt

# List files in the current directory
list_of_files = os.listdir() 

for f in list_of_files:
    # Creation time
    ct = os.path.getctime(f)

    # Modification time
    mt = os.path.getmtime(f)

    # Check the human readable string
    print(f"file: {f} "
          f"creation: {dt.fromtimestamp(ct)} "
          f"modification: {dt.fromtimestamp(mt)} ")

But be careful about converting time-zones! You don't want to give the code a local time zone and remove the files based on UTC

Some useful resources:

Pedram
  • 921
  • 1
  • 10
  • 17