HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Days ago, days from now, add and subtract dates

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
fromsubtractanddatesagoaddpythondaysnow

Problem

To calculate the date of n days ago from today, simply use datetime.date.today() to get the current day and datetime.timedelta to subtract n days from it.
Similarly, to calculate the date of n days from today, use datetime.date.today() to get the current day and datetime.timedelta to add n days to it.
In order to calculate the date of n days from the given date, you can use datetime.timedelta and the + operator to calculate the new datetime.datetime value after adding n days to d.
Finally, to calculate the date of n days before the given date, you can use datetime.timedelta and the - operator to calculate the new datetime.datetime value after subtracting n days from d.

Solution

from datetime import timedelta, date

def days_ago(n):
  return date.today() - timedelta(n)

days_ago(5) # date(2020, 10, 23)


In order to calculate the date of n days from the given date, you can use datetime.timedelta and the + operator to calculate the new datetime.datetime value after adding n days to d.
Finally, to calculate the date of n days before the given date, you can use datetime.timedelta and the - operator to calculate the new datetime.datetime value after subtracting n days from d.

Code Snippets

from datetime import timedelta, date

def days_ago(n):
  return date.today() - timedelta(n)

days_ago(5) # date(2020, 10, 23)
from datetime import timedelta, date

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

days_from_now(5) # date(2020, 11, 02)
from datetime import date, datetime, timedelta

def add_days(n, d = datetime.today()):
  return d + timedelta(n)

add_days(5, date(2020, 10, 25)) # date(2020, 10, 30)
add_days(-5, date(2020, 10, 25)) # date(2020, 10, 20)

Context

From 30-seconds-of-code: days-ago-days-from-now-add-subtract-dates

Revisions (0)

No revisions yet.