开发者

Convert a string to datetime object in python

I have a date string defined as followe开发者_如何学运维d:

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


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.


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')


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜