pythonhunter pythonhunter - 1 month ago 7
Python Question

Python -Remove Time from Datetime String

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
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()
Comments