What am I doing wrong here?
import datetime
someday = datetime.datetime(2014, 9, 23, 0, 0)
someday = datetime.datetime.strptime(someday[:10], '%Y-%m-%d')
print someday
Error:
TypeError: 'datetime.datetime' object has no attribute '__getitem__'
someday
is a datetime
object, which does not support slicing. So, doing someday[:10]
raises a TypeError
.
You need to convert someday
into a string before you slice it:
someday = datetime.datetime.strptime(str(someday)[:10], '%Y-%m-%d')
Demo:
>>> 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'
>>>