Reputation: 47
I'm trying to convert non padded string to date in python and getting following error:
e_dataframe['Modified_Date'] = pd.to_datetime(e_dataframe['Modified_Date'], format='%d/%m/%y %I:%M %p')
ValueError: time data '1/08/2018 4:41 PM' does not match format '%d/%m/%y %I:%M %p' (match)
The format is similar still getting an error.
Upvotes: 0
Views: 182
Reputation: 1122002
%y
matches a year with two digits, omitting the century. Your input has a 4 digit year, so you need to use %Y
:
'%d/%m/%Y %I:%M %p'
When in doubt, use datetime.strptime()
with a substring of your input so you can see what parts work and what parts fail:
>>> import datetime
>>> datetime.datetime.strptime('1', '%d')
datetime.datetime(1900, 1, 1, 0, 0)
>>> datetime.datetime.strptime('1/08', '%d/%m')
datetime.datetime(1900, 8, 1, 0, 0)
>>> datetime.datetime.strptime('1/08/2018', '%d/%m/%y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.7/_strptime.py", line 362, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 18
The error indicates that %y
only processed the 20
part of the year, telling us that it was not the correct placeholder for the 2018
input.
Upvotes: 3