datetime command line argument in python 2.4
I want to pass a da开发者_StackOverflow中文版tetime 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)
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)
精彩评论