Python provides a built-in module called datetime to manipulate dates and times. In a previous post, we say how to extract the year from a date using this module (the same logic can be used for days and months, by the way). Let’s see now how we can use this module to add days to a date object we have in Python.
Table of Contents
Create a date object
The first step is to create a date object. You can create a date object from a string simply using the following code.
from datetime import datetime
date_str = '2022-01-01'
date_obj = datetime.strptime(date, '%Y/%m/%d')
Code language: Python (python)
You can also create one directly without having to create a string first:
from datetime import datetime
date_obj = datetime(2022,1,1)
Code language: Python (python)
Add days to a date using timedelta
One key characteristics of a date object is that its attributes are immutable, and hence you cannot add days by running the following code:
date_obj.day = date_obj.day + 5
Code language: Python (python)
It makes sense though, because adding a day does not always mean adding one to the attribute day of the datetime object. Indeed, if you create a date object representing the last day of a month, the value of day will actually decrease while the value of month will increase.
Luckily for us, the datetime module comes with a timedelta class, which represents the duration. It allows us to add days, month, years etc… to a datetime object or even calculate the difference between two dates. Let’s see a simple example:
from datetime import datetime, timedelta
today = datetime.today()
tomorrow = today + timedelta(days=1)
print(tomorrow)
Code language: Python (python)
The output of this code will depend on when you execute it, but it will always return tomorrow. Please note that you can indicate seconds, microseconds, milliseconds, minutes, hours and weeks for the timedelta object. If you need other duration (like years for instance), you’d have to use the relativedelta from the dateutil module, providing powerful extensions to the standard datetime module, available in Python.
from datetime import datetime
import dateutil.relativedelta as relativedelta
today = datetime.today()
today_next_year = today + relativedelta.relativedelta(years=1)
Code language: Python (python)
I’d stick with timedelta if you can though, to avoid adding extra dependency within your code.