2011-04-07 61 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