2011-04-07 18 views
11

我們的團隊在某些情況下需要使用Python 2.4.1。 strptime不存在於datetime.datetime模塊中在Python 2.4.1:datetime.datetime.strptime在Python中不存在2.4.1

Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import datetime 
>>> datetime.datetime.strptime 
Traceback (most recent call last): 
    File "<string>", line 1, in <fragment> 
AttributeError: type object 'datetime.datetime' has no attribute 'strptime' 

如2.6反對:

Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import datetime 
>>> datetime.datetime.strptime 
<built-in method strptime of type object at 0x1E1EF898> 

雖然打字時,我發現它的2.4.1時間模塊中:

Python 2.4.1 (#65, Mar 30 2005, 09:16:17) [MSC v.1310 32 bit (Intel)] 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import time 
>>> time.strptime 
<built-in function strptime> 

我認爲strptime在某一點上移動?什麼是檢查這樣的事情的最好方法。我試圖通過python的發佈歷史,但找不到任何東西。

回答

18

請注意,strptime仍然在time模塊中,即使是2.7.1以及datetime

但是,如果你在最近的版本看documentation for datetime,你會看到這樣的strptime下:

這相當於datetime(*(time.strptime(date_string, format)[0:6]))

所以你可以使用該表達式來代替。請注意,相同的條目也說「版本2.5中的新功能」。

+0

這說明了一切 - 我認爲我檢查了文檔,看它是否在提及時提及,但我顯然錯過了這一點。謝謝! – Nathan 2011-04-07 19:09:57

1

新方法通常記錄在圖書館參考中,「新聞從版本....」 我不記得方法已經消失或被刪除...這將是一個向後兼容性犯規。受到移除的方法通常會被官方棄用,並帶有DeprecationWarning。

11

我也有類似的問題。

基於丹尼爾的回答,這個工作對我來說,當你不知道下哪個Python版本(2.4 VS 2.6)的腳本將運行:

from datetime import datetime 
import time 

if hasattr(datetime, 'strptime'): 
    #python 2.6 
    strptime = datetime.strptime 
else: 
    #python 2.4 equivalent 
    strptime = lambda date_string, format: datetime(*(time.strptime(date_string, format)[0:6])) 

print strptime("2011-08-28 13:10:00", '%Y-%m-%d %H:%M:%S') 

-Fi

相關問題