0

I am trying to write a script in Python to upload a series of photos depending on the dates they were created. I am having an issue of comparing the dates of each of the files to a date before and after the dates I want so that I can create an array to loop through for my uploading. Here is what I have:

from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, datetime

array = []

area = "/home/user/blah"
# Edit the path to match your desired folder between the ""
os.chdir(area)
retval = os.getcwd()
# Puts you in the desired directory

dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))

for cdate, path in sorted(entries):
    filedate = time.ctime(cdate)
    if filedate < datetime.date(2015,03,13) and filedate > datetime.date(2015,02,17):
        print time.ctime(cdate)
        print os.path.basename(path)

Is there a way to do this with ctime or is there a better way?

Illyduss
  • 161
  • 1
  • 3
  • 11

2 Answers2

0

There's no real need to os.chdir() here. Dealing with absolute filenames is fine. You can simplify the selection criteria using a list-comp, datetime, os.path.isfile and os.path.getctime, eg:

import os
from datetime import datetime

files = [
    fname
    for fname in sorted(os.listdir(dirpath))
    if os.path.isfile(fname) and
    datetime(2015, 2, 17) <= datetime.fromtimestamp(os.path.getctime(fname)) <= datetime(2015, 3, 13)
]

This returns a list of all files between two dates...

I'm guessing you're using Python 2.x because otherwise datetime.date(2015,03,13) would be giving you a SyntaxError in 3.x. Be wary of that as 03 is an octal literal and just happens to work in your case - but 08/09 will break as they're invalid for octal.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

ctime return the string representation, if you want to compare with time, you should compare the timestamp or datetime class.

for cdate, path in sorted(entries):
    # compare by timestamp
    #if cdate < time.mktime(datetime.date(2015,03,13).timetuple()) and \
    #    cdate > time.mktime(datetime.date(2014,02,17).timetuple()):

    # compare by datetime
    filedate = datetime.datetime.fromtimestamp(cdate)
    if filedate < datetime.datetime(2015,03,13) and \
            filedate > datetime.datetime(2014,02,17):
        print time.ctime(cdate)
        print os.path.basename(path)
SolaWing
  • 1,652
  • 12
  • 14
  • Oh, cool I thought fromtimestamp would only work with timedelta. Cool, I just learned something. Thanks! – Illyduss Mar 19 '15 at 05:19