81

I would like to write a script where I give Python a number of days (let's call it d) and it gives me the date we were d days ago.

I am struggling with the module datetime:

import datetime 

tod = datetime.datetime.now()
d = timedelta(days = 50) 
a = tod - h 
Type Error : unsupported operand type for - : "datetime.timedelta" and 
"datetime.datetime" 
Amir Shabani
  • 3,857
  • 6
  • 30
  • 67
Dirty_Fox
  • 1,611
  • 4
  • 20
  • 24
  • 1
    What is `h` supposed to be? – khelwood Feb 01 '15 at 22:46
  • possible duplicate of [How can I subtract a day from a python date?](http://stackoverflow.com/questions/441147/how-can-i-subtract-a-day-from-a-python-date) – jfs Feb 02 '15 at 12:51

5 Answers5

106

You have mixed something up with your variables, you can subtract timedelta d from datetime.datetime.now() with no issue:

import datetime 
tod = datetime.datetime.now()
d = datetime.timedelta(days = 50)
a = tod - d
print(a)
2014-12-13 22:45:01.743172
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • you can also format the date with the method strftime(), e.g. get it in local date format, get just date (without time), etc.etc. At print write print(strftime( %x)) for local vesrion of date. All the legal formats here: https://www.w3schools.com/python/python_datetime.asp – darthcharmander Jun 24 '22 at 16:00
34

Below code should work

from datetime import datetime, timedelta

N_DAYS_AGO = 5

today = datetime.now()    
n_days_ago = today - timedelta(days=N_DAYS_AGO)
print today, n_days_ago
Amaresh Narayanan
  • 4,159
  • 3
  • 20
  • 22
11

If your arguments are something like, yesterday,2 days ago, 3 months ago, 2 years ago. The function below could be of help in getting the exact date for the arguments. You first need to import the following date utils

import datetime
from dateutil.relativedelta import relativedelta

Then implement the function below

def get_past_date(str_days_ago):
    TODAY = datetime.date.today()
    splitted = str_days_ago.split()
    if len(splitted) == 1 and splitted[0].lower() == 'today':
        return str(TODAY.isoformat())
    elif len(splitted) == 1 and splitted[0].lower() == 'yesterday':
        date = TODAY - relativedelta(days=1)
        return str(date.isoformat())
    elif splitted[1].lower() in ['hour', 'hours', 'hr', 'hrs', 'h']:
        date = datetime.datetime.now() - relativedelta(hours=int(splitted[0]))
        return str(date.date().isoformat())
    elif splitted[1].lower() in ['day', 'days', 'd']:
        date = TODAY - relativedelta(days=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['wk', 'wks', 'week', 'weeks', 'w']:
        date = TODAY - relativedelta(weeks=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['mon', 'mons', 'month', 'months', 'm']:
        date = TODAY - relativedelta(months=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['yrs', 'yr', 'years', 'year', 'y']:
        date = TODAY - relativedelta(years=int(splitted[0]))
        return str(date.isoformat())
    else:
        return "Wrong Argument format"

You can then call the function like this:

print get_past_date('5 hours ago')
print get_past_date('yesterday')
print get_past_date('3 days ago')
print get_past_date('4 months ago')
print get_past_date('2 years ago')
print get_past_date('today')
  • Actually Im looking for the inverse (datetime to "Time Difference") but, Im gonna keep this, its cool! Take my like bro! – Jcc.Sanabria Oct 27 '22 at 14:28
11

we can get the same as like this ,It is applicable for past and future dates also.

Current Date:

import datetime
Current_Date = datetime.datetime.today()
print (Current_Date)

Previous Date:

import datetime
Previous_Date = datetime.datetime.today() - datetime.timedelta(days=1) #n=1
print (Previous_Date)

Next-Day Date:

import datetime
NextDay_Date = datetime.datetime.today() + datetime.timedelta(days=1)
print (NextDay_Date)
Sachin
  • 1,460
  • 17
  • 24
0

For the applications where you want to provide user convenient input format of relative dates you might look at parser from dateparser Python package. It is a solution along the lines proposed by Simeon Babatunde but more capable. The usage is as:

from dateparser import parse

date_time = parse('10 days ago')
``
izkeros
  • 790
  • 1
  • 5
  • 23