2010-03-11 96 views
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) 

回答

16

去的time模块,并已经有strptime 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) 
+0

这是完美的。我注意到了time.strptime,但是我对python并不熟悉,并没有意识到使用切片符号将时间转换为日期时间是多么容易。 谢谢! – 2010-03-11 21:35:51

+0

@Ike,不客气! – 2010-03-11 21:38:12

+1

与此同时,python库已经更新,所以你不需要使用时间。现在,只需使用:datetime.datetime.strptime() – 2015-11-23 19:23:04