2017-04-10 215 views
0

雖然我通過"%a %b %d %H:%M:%S %Z %Y"作爲time.strptime()中的格式字符串,但它在'%a %b %d %H:%M:%S %Y'上運行,因此導致錯誤。任何想法可能會導致它?time.strptime()不遵守格式規定

同樣的事情在python控制檯中運行完美,但在實際的代碼中沒有。

Exception in thread Thread-7: 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner 
    self.run() 
    File "/usr/lib/python2.7/threading.py", line 754, in run 
    self.__target(*self.__args, **self.__kwargs) 
    File "proxy.py", line 137, in listenThread 
    response = self.fetchRequest(raw_request, request) 
    File "proxy.py", line 114, in fetchRequest 
    if request['type'] == "GET" and self.is_cachable(request, response_headers): 
    File "proxy.py", line 100, in is_cachable 
    requestTime = time.mktime(time.strptime(self.request_log[request['url']][len(self.request_log[request['url']])-3]), "%a %b %d %H:%M:%S %Z %Y") 
    File "/usr/lib/python2.7/_strptime.py", line 478, in _strptime_time 
    return _strptime(data_string, format)[0] 
    File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime 
    (data_string, format)) 
ValueError: time data 'Mon Apr 10 22:52:38 IST 2017' does not match format '%a %b %d %H:%M:%S %Y' 
+0

請顯示導致問題的實際代碼。 – DyZ

+0

您在「Apr」和「10」之間獲得了額外的空間。 –

+0

您必須運行的代碼不是您認爲的自己。 Python不會隨機使用不同的硬編碼字符串。 –

回答

1

Actualy我剛剛作出了一個非常愚蠢的錯誤

requestTime = time.mktime(time.strptime(self.request_log[request['url']][len(self.request_log[request['url']])-3]), "%a %b %d %H:%M:%S %Z %Y") 

括號的順序是錯誤的上面,它應該是這樣的

requestTime = time.mktime(time.strptime(self.request_log[request['url']][len(self.request_log[request['url']])-3], "%a %b %d %H:%M:%S %Z %Y")) 

我其實是隻傳遞時間字符串時間.strptime()離開格式
對不起所引起的問題

+1

啊,的確,這是*默認格式.. –

1

%Z的價值來源於附着在datetime對象tzinfo對象,但沒有datetime對象(因此沒有tzinfo要麼)如果你使用strptime()代替strftime()。事實上,標準Python庫附帶的唯一tzinfo對象是固定偏移量timezone對象,然後僅在Python 3中。除標準UTC值外,標準庫沒有這些的標準列表;相反,您需要根據需要創建它們,或者使用pytz。因此,Python標準庫沒有將任意三字母代碼翻譯成時區的機制。它應該能夠處理'UTC',一些同義詞,也許你的本地時間是由系統區域設置返回的,但這就是它。

(提示:對於大多數人來說,pytz是正確的事情使用。)

三個字母組成的代碼是notgloballyunique無論如何,所以不存在「正確」的方式做你問什麼。您需要具有類似Olson database標識符的內容(例如America/New_York大致與東部標準/日光時間同義)。

+0

即使對於'%Z',回溯也應該顯示傳入的格式。這裏不是這種情況。我可以得出的唯一結論是*服務器正在運行陳舊的字節碼*。源代碼更新。 –

+0

@MartijnPieters:如果OP的源代碼與OP的字節碼相匹配,那將會很不錯,但不幸的是,這不會解決OP的實際問題,那就是他們正在嘗試做一些不可能的事情。 – Kevin

+0

當然,但*這是錯誤是關於*。使用的實際格式不包含'%Z'。 –