+1 vote
in Programming Languages by (10.1k points)

I am trying to add days to a date using the Python datetime module. However, the code gives an error. How to fix the error?

Here is the code:

>>> from datetime import datetime

>>> d1='2007-01-01'

>>> d1=datetime.strptime(d1, "%Y-%m-%d")

>>> d1

datetime.datetime(2007, 1, 1, 0, 0)

>>> d1+365

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'int'

1 Answer

+1 vote
by (77.0k points)
selected by
 
Best answer

As it is obvious from the error message, you cannot add an integer to a datetime object. 

To add days to a given date, use the timedelta() function from the datetime module with argument "days". 

Here is how to fix your code:

>>> from datetime import datetime,timedelta
>>> d1='2007-01-01'
>>> d1=datetime.strptime(d1, "%Y-%m-%d")
>>> d1
datetime.datetime(2007, 1, 1, 0, 0)
>>> d1+timedelta(days=365)
datetime.datetime(2008, 1, 1, 0, 0)

Related questions


...