Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to datetime object in python

Tags:

python

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

like image 541
james Avatar asked May 03 '11 10:05

james


1 Answers

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.

like image 90
eumiro Avatar answered Nov 14 '22 21:11

eumiro