Friday, June 3, 2016

PI Critter Cam Day 7: Is the File Old Enough to Delete?

As promised, I'm working on figuring out whether a critter_cam pic is old enough to be deleted.

To figure this out, we need to figure out our expiration date.  We did that last time.

To get the age of a file, you've got to use the os.path module, which comes with the PI version of Python.

That module comes with a function that pulls the creation date and the modification date for you.

os.path.getmtime('/home/pi/Pictures/critter_cam/2016_05_23_19_41_16.jpg'))

HOWEVER, it'll return it in a long decimal value representing the date and time.  NOT HELPFUL.

The datetime module, however, can handle this for you.  It has a fromtimestamp function that'll turn it into a legit datetime format you can compare your expiration date to the file date.

All together now:

#import our needed modules.
import datetime, os.path

#create our expiration date
current_date = datetime.datetime.today()
#The variable representing the duration we want to subtract to create our expiration date.
y = datetime.timedelta(weeks = 2)
#And create our expiration date variable.
exp_date = current_date - y

#get the modification date for the picture file and convert it to a legit datetime value.
file_date = datetime.datetime.fromtimestamp(os.path.getmtime('/home/pi/Pictures/critter_cam/2016_05_23_19_41_16.jpg'))

#And see if the file_date is old enough to be deleted
#If it returns TRUE, we should delete it.  
exp_date > file_date

Next time, we'll put in a loop to check all the files in our critter cam folder and delete the ones that meet this criteria.

No comments: