Search code examples
pythonpython-2.7datestamp

Open files older than 3 days of date stamp in file name - Python 2.7


** Problem ** I'm trying to open (in python) files older than 3 days of the date stamp which is in the current name. Example: 2016_08_18_23_10_00 - JPN - MLB - Mickeymouse v Burgerface.ply. So far I can create a date variable, however I do not know how to search for this variable in a filename. I presume I need to convert it to a string first?

from datetime import datetime, timedelta
import os
import re
path = "C:\Users\michael.lawton\Desktop\Housekeeper"

## create variable d where current date time is subtracted by 3 days ##

days_to_subtract = 3
d = datetime.today() - timedelta(days=days_to_subtract)

print d

## open file in dir where date in filename = d or older ##

for filename in os.listdir(path):
if re.match(d, filename):
    with open(os.path.join(path, filename), 'r') as f:
        print line,

Any help will be much appreciated


Solution

  • You can use strptime for this. It will convert your string (assuming it is correctly formatted) into a datetime object which you can use to compare if your file is older than 3 days based on the filename:

    from datetime import datetime
    
    ...
    
    lines = []
    for filename in os.listdir(path):
      date_filename = datetime.strptime(filename.split(" ")[0], '%Y_%m_%d_%H_%M_%S')
      if date_filename < datetime.datetime.now()-datetime.timedelta(days=days_to_subtract):
        with open(os.path.join(path, filename), 'r') as f:
          lines.extend(f.readlines()) # put all lines into array
    

    If the filename is 2016_08_18_23_10_00 - JPN - MLB - Mickeymouse v Burgerface.ply the datetime part will be extracted with filename.split(" ")[0]. Then we can use that to check if it is older than three days using datetime.timedelta