6

I have a date string defined as followed:

datestr = '2011-05-01'

I want to convert this into a datetime object so i used the following code

dateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d')
print dateobj

But what gets printed is: 2011-05-01 00:00:00. I just need 2011-05-01. What needs to be changed in my code ?

Thank You

2
  • This is a question that could easily have been answered by reading the documentation. Commented May 3, 2011 at 11:05
  • 1
    @BjörnPollex I just found this question and it helped me within 10 seconds. Finding the answer on the documentation page would have taken me a lot longer than that. StackOverflow is popular for a reason, and it's not a bad reason. Commented Jan 15, 2016 at 17:56

3 Answers 3

12

dateobj.date() will give you the datetime.date object, such as datetime.date(2011, 5, 1)

Use:

dateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d').date()

See also: Python documentation on datetime.

Sign up to request clarification or add additional context in comments.

2 Comments

Kinda lame that it's necessary to create a datetime object and then throw away the time...
@MuMind: In this simple case, you could also use datetime.date(*map(int, datestr.split("-"))) to create a date object directly.
2

As the name suggests, datetime objects always contain a date and a time. If you don't need the time, simply ignore it. To print it in the same format as before, use

print dateobj.strftime('%Y-%m-%d')

Comments

1
dateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d').date()
print dateobj

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.