Convert string to datetime object in python

I have a date string defined as follows:

datestr = '2011-05-01' 

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

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

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

thanks

+6
source share
3 answers

dateobj.date() will provide you with a datetime.date object, e.g. datetime.date(2011, 5, 1)

Using:

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

See also: Python documentation on datetime .

+12
source

As the name implies, datetime objects always contain date and time. If you do not need time, just ignore it. To print it in the same format as before, use

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

Source: https://habr.com/ru/post/887181/


All Articles