30秒学会 Python 片段 · 2022年12月10日

30秒学会 Python 片段 – Days from now

Calculates the date of n days from today.

  • Use datetime.date.today() to get the current day.
  • Use datetime.timedelta to add n days from today’s date.

代码实现

from datetime import timedelta, date

def days_from_now(n):
  return date.today() + timedelta(n)

使用样例

days_from_now(5) # date(2020, 11, 02)

翻译自:https://www.30secondsofcode.org/python/s/days-from-now