How to find the date n days ago in Python?

Python 2.7DateDatetimeTimedelta

Python 2.7 Problem Overview


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" 

Python 2.7 Solutions


Solution 1 - Python 2.7

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

Solution 2 - Python 2.7

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

Solution 3 - Python 2.7

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

Solution 4 - Python 2.7

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDirty_FoxView Question on Stackoverflow
Solution 1 - Python 2.7Padraic CunninghamView Answer on Stackoverflow
Solution 2 - Python 2.7Amaresh NarayananView Answer on Stackoverflow
Solution 3 - Python 2.7Simeon BabatundeView Answer on Stackoverflow
Solution 4 - Python 2.7SachinView Answer on Stackoverflow