Laurel Laurel - 1 year ago 73
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, 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

But I get the following error:

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

What could be the reason?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download