Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a date to a script in Python?

I have a script for deleting images older than a date.

Can I pass this date as an argument when I call to run the script?

Example: This script delete_images.py deletes images older than a date (YYYY-MM-DD)

python delete_images.py 2010-12-31

Script (works with a fixed date (xDate variable))

import os, glob, time

root = '/home/master/files/' # one specific folder
#root = 'D:\\Vacation\\*'          # or all the subfolders too
# expiration date in the format YYYY-MM-DD

### I have to pass the date from the script ###
xDate = '2010-12-31' 

print '-'*50
for folder in glob.glob(root):
    print folder
    # here .jpg image files, but could be .txt files or whatever
    for image in glob.glob(folder + '/*.jpg'):
        # retrieves the stats for the current jpeg image file
        # the tuple element at index 8 is the last-modified-date
        stats = os.stat(image)
        # put the two dates into matching format    
        lastmodDate = time.localtime(stats[8])
        expDate = time.strptime(xDate, '%Y-%m-%d')
        print image, time.strftime("%m/%d/%y", lastmodDate)
        # check if image-last-modified-date is outdated
        if  expDate > lastmodDate:
            try:
                print 'Removing', image, time.strftime("(older than %m/%d/%y)", expDate)
                os.remove(image)  # commented out for testing
            except OSError:
                print 'Could not remove', image 
like image 249
AurumAustralis Avatar asked Nov 19 '11 23:11

AurumAustralis


People also ask

How do you load a date in Python?

Example 1: Python get today's date today() method to get the current local date. By the way, date. today() returns a date object, which is assigned to the today variable in the above program. Now, you can use the strftime() method to create a string representing date in different formats.

How do I print a date in YYYY-MM-DD in Python?

strftime() Function to Format Date to YYYYMMDD in Python. The strftime() is used to convert a datetime object to a string with a given format. We can specify the format for YYYY-MM-DD in the function as %Y-%m-%d . Note that this function returns the date as a string.


2 Answers

The quick but crude way is to use sys.argv.

import sys
xDate = sys.argv[1]

A more robust, extendable way is to use the argparse module:

import argparse

parser=argparse.ArgumentParser()
parser.add_argument('xDate')
args=parser.parse_args()

Then to access the user-supplied value you'd use args.xDate instead of xDate.

Using the argparse module you automatically get a help message for free when a user types

delete_images.py -h

It also gives a helpful error message if the user fails to supply the proper inputs.

You can also easily set up a default value for xDate, convert xDate into a datetime.date object, and, as they say on TV, "much, much more!".


I see later in you script you use

expDate = time.strptime(xDate, '%Y-%m-%d')

to convert the xDate string into a time tuple. You could do this with argparse so args.xDate is automatically a time tuple. For example,

import argparse
import time

def mkdate(datestr):
    return time.strptime(datestr, '%Y-%m-%d')
parser=argparse.ArgumentParser()
parser.add_argument('xDate',type=mkdate)
args=parser.parse_args()
print(args.xDate)

when run like this:

% test.py 2000-1-1

yields

time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)

PS. Whatever method you choose to use (sys.argv or argparse), it would be a good idea to pull

expDate = time.strptime(xDate, '%Y-%m-%d')

outside of the for-loop. Since the value of xDate never changes, you only need to compute expDate once.

like image 69
unutbu Avatar answered Oct 18 '22 21:10

unutbu


Little bit more polish to unutbu's answer:

import argparse
import time

def mkdate(datestr):
  try:
    return time.strptime(datestr, '%Y-%m-%d')
  except ValueError:
    raise argparse.ArgumentTypeError(datestr + ' is not a proper date string')

parser=argparse.ArgumentParser()
parser.add_argument('xDate',type=mkdate)
args=parser.parse_args()
print(args.xDate)
like image 27
Wonil Avatar answered Oct 18 '22 20:10

Wonil