Open files older than 3 days of date stamp in file name - Python 2.7
<p>** 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?</p>

<pre><code>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,
</code></pre>

<p>Any help will be much appreciated</p>

<p>You can use <code>strptime</code> 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:</p>

<pre><code>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 &lt; 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
</code></pre>

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

python python-2.7 datestamp