3

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__'
user2242044
  • 8,803
  • 25
  • 97
  • 164
  • What is the actual problem you're trying to solve here? If it's just "get the date part of a datetime," you can use the `.date()` method. – John Zwinck Jan 12 '15 at 02:06
  • possible duplicate of [TypeError: 'datetime.date' object has no attribute '\_\_getitem\_\_'](http://stackoverflow.com/questions/20831994/typeerror-datetime-date-object-has-no-attribute-getitem) – GLHF Jan 12 '15 at 02:07

2 Answers2

7

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'
>>>
  • The conversions to and from string are unnecessary here. Just [use `print someday.date()` instead](http://stackoverflow.com/a/27987553/4279). – jfs Jan 16 '15 at 15:42
  • @J.F.Sebastian - My answer was mainly focused on why the OP's slice was failing and how to get it working (with slicing). However, I agree that calling `.date()` is a lot more pythonic in this case. +1 for mentioning it. :) –  Jan 16 '15 at 16:08
1

someday is not a string therefore you won't get the substring by applying [:10]. It is a datetime object.

To get the date from the datetime object, just call .date() method:

print someday.date()

No need to convert to convert someday to string using str() only to convert it immediately back using datetime.strptime().

jfs
  • 399,953
  • 195
  • 994
  • 1,670