Dirty_Fox
Dirty_Fox

Reputation: 1751

How to find the date n days ago in Python?

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" 

Upvotes: 93

Views: 142918

Answers (6)

kiran
kiran

Reputation: 11

from datetime import datetime,timedelta   
past = datetime.now() - timedelta(days=50)
print(past.strftime("%d/%m/%Y, %H:%M:%S"))

Upvotes: 1

izkeros
izkeros

Reputation: 918

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')
``

Upvotes: 2

Sachin
Sachin

Reputation: 1704

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)

Upvotes: 12

Amaresh Narayanan
Amaresh Narayanan

Reputation: 4435

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

Upvotes: 39

Simeon Babatunde
Simeon Babatunde

Reputation: 416

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')

Upvotes: 11

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

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

Upvotes: 119

Related Questions