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__'
2

2 Answers 2

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'
>>>
Sign up to request clarification or add additional context in comments.

2 Comments

The conversions to and from string are unnecessary here. Just use print someday.date() instead.
@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. :)
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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.