On this instance, we’ll see the best way to add days to dates in python.
So as to add days to a date in python, you merely want to make use of the timedelta()
class that you must import from the datetime
module.
For instance:
dateplustwo = aDate + timedelta(days=2).
We handed a days argument to the timedelta
class and added two days to the date.
Right here is the entire working instance:
>>> from datetime import datetime, date, timedelta
>>> at the moment = datetime.at the moment()
>>> print(at the moment + timedelta(days=1))
2022-09-30 20:42:58.812066
The datetime.at the moment()
technique returns the present native datetime.
This will also be used with date
as a substitute of datetime
as follows:
>>> at the moment = date.at the moment()
>>> print(at the moment + timedelta(days=3))
2022-10-02
The date.at the moment technique returns a date object that represents the present native date.
Don’t neglect to import the datetime or date and timedelta lessons from the datetime module.
We are able to additionally use a date string however we first have to convert it a datetime object earlier than including days to it. Here’s a working instance:
>>> at the moment = '2022-09-29' # format: yyyy-mm-dd
>>> datetime.strptime(at the moment, '%Y-%m-%d')
datetime.datetime(2022, 9, 29, 0, 0)
>>> print(at the moment)
2022-09-29
>>> myday = datetime.strptime(at the moment, '%Y-%m-%d')
>>> print(myday + timedelta(days=2))
2022-10-01 00:00:00
The datetime.timedelta class takes the times we have to add to the date or datetime objects.
We formatted the date string as yyyy-mm-dd
and we used the strptime()
technique to transform the string to a datetime object, equivalent to the supplied format, that we are able to use with the timedelta()
class.