date 2.4中没有datetime.datetime.strptime

Nat*_*han 11 python datetime

在某些情况下,我们的团队必须使用Python 2.4.1.在Python 2.4.1 strptime中的datetime.datetime模块中不存在:

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'
Run Code Online (Sandbox Code Playgroud)

与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>
Run Code Online (Sandbox Code Playgroud)

打字时,我在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>
Run Code Online (Sandbox Code Playgroud)

我认为它strptime在某些时候移动了吗?检查这样的事情的最佳方法是什么.我尝试查看python的发布历史但找不到任何内容.

Dan*_*man 19

请注意,即使在2.7.1以及之中,strptime它仍然在time模块中datetime.

但是,如果您在最近的版本中查看datetime文档,您将在strptime以下内容中看到:

这相当于 datetime(*(time.strptime(date_string, format)[0:6]))

所以你可以使用那个表达式.请注意,相同的条目也会显示"2.5版中的新功能".


cod*_*rfi 11

我也有类似的问题.

基于Daniel的回答,当你不确定脚本将在哪个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')
Run Code Online (Sandbox Code Playgroud)

-Fi