python - 日期时间类型错误 : 'datetime.datetime' object has no attribute '__getitem__'

标签 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__'

最佳答案

someday 是一个datetime对象,不支持切片。因此,执行 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'
>>>

关于python - 日期时间类型错误 : 'datetime.datetime' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894363/

相关文章:

python 关键代码和 configparser 帮助

python - 使用Python在字符串中查找unicode字符

r - 如何从 strptime() 中仅提取时间?

r - 计算 R 中两个事件(给定日期和时间)之间的时间差

c++ strptime在解析时忽略时区

python - Google App Engine TextProperty 和 UTF-8 : When to Encode/Decode

python - 如何根据另一列的特定值从一列中删除 NaN

python - 在 numpy 中从多个集合中选取并分配多个子集

python - 如何使用 re.compile 和 re.findall 删除括号内的文本?

python - 使用字典将月份数字转换为月份名称的基本 Python 编程