rodrigosillos rodrigosillos - 6 months ago 36
Python Question

I need to convert datetime to date without seconds in python

I need to convert datetime to date without seconds in python, how to execute this:

from datetime import datetime
dt = datetime.strptime('2016-06-01 16:05:20', '%Y-%m-%d').date()
print dt


Result:

Traceback (most recent call last):
File "teste.py", line 5, in <module>
dt = datetime.strptime('2016-06-01 16:05:20', '%Y-%m-%d').date()
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 16:05:20


I've tried everything

Can help?

Answer

Even though you're going to discard the time, you still need to include it in your format string, since it exists in the string you're parsing. strptime() doesn't know that you don't care about the time, it just needs to match the input against the format string.

dt = datetime.strptime('2016-06-01 16:05:20', '%Y-%m-%d %H:%M:%S').date()
Comments