9

I want to pass a datetime value into my python script on the command line. My first idea was to use optparse and pass the value in as a string, then use datetime.strptime to convert it to a datetime. This works fine on my machine (python 2.6), but I also need to run this script on machines that are running python 2.4, which doesn't have datetime.strptime.

How can I pass the datetime value to the script in python 2.4?

Here's the code I'm using in 2.6:

parser = optparse.OptionParser()
parser.add_option("-m", "--max_timestamp", dest="max_timestamp",
                  help="only aggregate items older than MAX_TIMESTAMP", 
                  metavar="MAX_TIMESTAMP(YYYY-MM-DD HH24:MM)")
options,args = parser.parse_args()
if options.max_timestamp:
    # Try parsing the date argument
    try:
        max_timestamp = datetime.datetime.strptime(options.max_timestamp, "%Y-%m-%d %H:%M")
    except:
        print "Error parsing date input:",sys.exc_info()
        sys.exit(1)

1 Answer 1

17

Go by way of the time module, which did already have strptime in 2.4:

>>> import time
>>> t = time.strptime("2010-02-02 7:31", "%Y-%m-%d %H:%M")
>>> t
(2010, 2, 2, 7, 31, 0, 1, 33, -1)
>>> import datetime
>>> datetime.datetime(*t[:6])
datetime.datetime(2010, 2, 2, 7, 31)
Sign up to request clarification or add additional context in comments.

3 Comments

This is perfect. I had noticed time.strptime but I'm new to python and didn't realize how easy it is to convert the time to a datetime using slice notation. Thanks!
In the meantime, the python library has been updated so you don't need to use time. Now, just use: datetime.datetime.strptime()
@StephenJohnson, yes, unless of course you need to support obsolete versions of Python as the OP (in his Q 5+ years ago) very specifically said he did -- in which case, knowing how to do things in those ancient versions is still pretty important:-).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.