8
我想在命令行中将datetime值传入我的python脚本。我的第一个想法是使用optparse并将值作为字符串传递,然后使用datetime.strptime将其转换为日期时间。这在我的机器(python 2.6)上正常工作,但我还需要在运行python 2.4的机器上运行此脚本,该机器没有datetime.strptime。python 2.4中的datetime命令行参数
如何将日期时间值传递给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)
这是完美的。我注意到了time.strptime,但是我对python并不熟悉,并没有意识到使用切片符号将时间转换为日期时间是多么容易。 谢谢! – 2010-03-11 21:35:51
@Ike,不客气! – 2010-03-11 21:38:12
与此同时,python库已经更新,所以你不需要使用时间。现在,只需使用:datetime.datetime.strptime() – 2015-11-23 19:23:04