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>To open all files in the given directory that contain a timestamp in their name older than 3 days:</p>

<pre><code>#!/usr/bin/env python2
import os
import time

DAY = 86400 # POSIX day in seconds
three_days_ago = time.time() - 3 * DAY
for filename in os.listdir(dirpath):
    time_string = filename.partition(" ")[0]
    try:
        timestamp = time.mktime(time.strptime(time_string, '%Y_%m_%d_%H_%M_%S'))
    except Exception: # can't get timestamp
        continue
    if timestamp &lt; three_days_ago: # old enough to open
        with open(os.path.join(dirpath, filename)) as file: # assume it is a file
            for line in file:
                print line,
</code></pre>

<p>The code assumes that the timestamps are in the local timezone. It may take DST transitions into account on platforms where C <code>mktime()</code> has access to <a href="https://en.wikipedia.org/wiki/Tz_database" rel="nofollow">the tz database</a> (if it doesn't matter whether the file is 72  or 73 hours old in your case then just ignore this paragraph).</p>

<p>Consider using file metadata such as "the last modification time of a file" instead of extracting the timestamp from its name: <code>timestamp = os.path.getmtime(path)</code>.</p>

python python-2.7 datestamp