datetime TypeError:' datetime.datetime'对象没有属性' __ getitem __'

时间:2015-01-12 02:03:23

标签: python python-2.7 strptime

我在这里做错了什么?

import datetime

someday = datetime.datetime(2014, 9, 23, 0, 0)

someday = datetime.datetime.strptime(someday[:10], '%Y-%m-%d')
print someday

错误:

TypeError: 'datetime.datetime' object has no attribute '__getitem__'

2 个答案:

答案 0 :(得分:6)

somedaydatetime对象,不支持切片。因此,执行someday[:10]会引发TypeError

在切片之前,您需要将someday转换为字符串:

someday = datetime.datetime.strptime(str(someday)[:10], '%Y-%m-%d')

演示:

>>> import datetime
>>> someday = datetime.datetime(2014, 9, 23, 0, 0)
>>>
>>> someday  # This is a datetime object
datetime.datetime(2014, 9, 23, 0, 0)
>>> someday[:10] # Does not support slicing
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'datetime.datetime' object has no attribute '__getitem__'
>>>
>>> str(someday) # This returns a string
'2014-09-23 00:00:00'
>>> str(someday)[:10] # Supports slicing
'2014-09-23'
>>>

答案 1 :(得分:1)

someday不是字符串,因此您无法通过应用[:10]来获取子字符串。它是datetime对象。

要从datetime对象获取日期,只需调用.date()方法:

print someday.date()

无需转换为使用somedaystr()转换为字符串,只能使用datetime.strptime()立即将其转换回来。