Laurel Laurel - 4 months ago 10
Python Question

Python: Getting Value Error while adding days to a particular date

I'm using Python to add 2 days to a particular date in Python. Using datetime.now(), I'm able to add 2 days. But not using a particular date. Here's the code:

import datetime

start_date = datetime.datetime.strptime('7/18/2016','%m/%d/%y')
date_to_start_predicting = start_date + datetime.timedelta(days=2) # Add 2 days
print(date_to_start_predicting)


But I get the following error:

Traceback (most recent call last):
File "C:/Users/Admin/Projects/DateAdd.py", line 3, in <module>
start_date = datetime.datetime.strptime('7/18/2016','%m/%d/%y')
File "C:\Python27\lib\_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 16


What could be the reason?

Answer

You are parsing the string '7/18/2016' with the format '%m/%d/%y'.

%y tries to parse the year part in 2 digits format (so the year of your date object is 1920). So 2016 becomes 20 and 16 is left over which is what the error says.

You should be using %Y (which parses the year in 4 digits format) instead of %y.