Display Python datetime without time

pythonhunter picture pythonhunter · Oct 2, 2014 · Viewed 146.3k times · Source

I have a date string and want to convert it to the date type:

I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.

    when = alldates[int(daypos[0])]
    print when, type(when)

    then = datetime.datetime.strptime(when, '%Y-%m-%d')
    print then, type(then)

This is what the output returns:

   2013-05-07 <type 'str'>
   2013-05-07 00:00:00 <type 'datetime.datetime'>

I need to remove the the time: 00:00:00.

Answer

Woody Pride picture Woody Pride · Oct 2, 2014
print then.date()

What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:

then = datetime.datetime.strptime(when, '%Y-%m-%d').date()