Python 2.4 中的 datetime 命令行参数
我想在命令行中把一个日期时间值传递给我的Python脚本。最开始我想用optparse这个工具,把这个值当成字符串传进去,然后用datetime.strptime把它转换成日期时间格式。在我的电脑上(使用的是Python 2.6)这样做没问题,但我还需要在一些使用Python 2.4的机器上运行这个脚本,而Python 2.4里没有datetime.strptime这个功能。
那么,我该如何在Python 2.4中把日期时间值传递给脚本呢?
这是我在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 个回答
17
可以通过 time
模块来实现,这个模块在2.4版本中就已经有了 strptime
这个功能:
>>> 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)