2015-04-24 90 views
-2

我有一個Python應用程序,我正在記錄數據庫中的try塊的成功和失敗。我最初在我的腳本中使用dateime.timedelta來計算datetime.datetime.now減5分鐘。我稍後使用datetime.datetime.strptime(last_time,「%m /%d /%Y%H:%M:%S%p」)將unicode時間戳轉換爲日期。最後,我想比較我的last_run和now_minus_5變量。我的腳本在下面;比較日期時間對象時遇到的問題

我沒有收到我的條件語句的輸出,它應該是true。

Start = datetime.datetime.now() 
    i = 5 
    i2= 10 
    now_minus_5 = Start - datetime.timedelta(minutes =i) 
    now_minus_10 = Start - datetime.timedelta(minutes =i2) 

order_fld = "Time" 
     return_flds = ["Time", "SUCCESS"] 
     where_str = """Time >= DATEADD(minute, -5, GETDATE()) AND SUCCESS = 'NO'""" 
     sql_clause = (None,'ORDER BY {} DESC'.format(order_fld)) 
     last_row = '' 
     with arcpy.da.SearchCursor(aTable, return_flds, where_clause=where_str, sql_clause=sql_clause) as cursor: 
      last_row = cursor.next() 
      last_time = last_row[0] 
      last_run = datetime.datetime.strptime(last_time,"%m/%d/%Y %H:%M:%S %p") 
      last_success = last_row[1] 

      print last_run 
      print last_success 

      if last_run >= now_minus_5: 
       print "true"` 
+1

什麼是價值'last_row'?請發佈一個可重現的例子 –

+1

另外,你的縮進全部搞砸了。糾正它會有幫助。 – bmhkim

+1

你確定'last_run'確實是'> = now_minus_5'嗎?我建議在你的條件之後加上一個else語句,並嘗試輸出參數給你的測試。或者更好的是,設置一個'pdb'斷點。 – bmhkim

回答

2

您看到的問題是由於對strptime()的錯誤輸入。

引用的Python docs on strftime and strptime behavior,爲%p notes列指的是注1和2.具體到你的情況是注2:「當與strptime()方法使用時,%p指令隻影響輸出時間字段,如果%I指令是用來解析小時。「

更新您的通話strptime修復無效行爲:

>>> import datetime 
>>> last_time = u'4/24/2015 4:34:10 PM' 
>>> last_run = datetime.datetime.strptime(last_time,"%m/%d/%Y %H:%M:%S %p") 
>>> last_run 
datetime.datetime(2015, 4, 24, 4, 34, 10) 
>>> last_run = datetime.datetime.strptime(last_time,"%m/%d/%Y %I:%M:%S %p") 
>>> last_run 
datetime.datetime(2015, 4, 24, 16, 34, 10)