2010-03-11 152 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