Calculates the date of n
days from the given date.
- Use
datetime.timedelta
and the+
operator to calculate the newdatetime.datetime
value after addingn
days tod
. - Omit the second argument,
d
, to use a default value ofdatetime.today()
.
代码实现
from datetime import datetime, timedelta
def add_days(n, d = datetime.today()):
return d + timedelta(n)
使用样例
from datetime import date
add_days(5, date(2020, 10, 25)) # date(2020, 10, 30)
add_days(-5, date(2020, 10, 25)) # date(2020, 10, 20)