How to find the date n days ago in Python?

Dir*_*Fox 9 datetime date timedelta python-2.7

Good evening chaps,

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" 
Run Code Online (Sandbox Code Playgroud)

Thanks for your help

Pad*_*ham 16

您有混合的东西了你的变量,你可以减去timedelta ddatetime.datetime.now()没有问题:

import datetime 
tod = datetime.datetime.now()
d = datetime.timedelta(days = 50)
a = tod - d
print(a)
2014-12-13 22:45:01.743172
Run Code Online (Sandbox Code Playgroud)


Ama*_*nan 14

下面的代码应该工作

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
Run Code Online (Sandbox Code Playgroud)


Sac*_*hin 11

我们可以得到与此相同的结果,它也适用于过去和未来的日期。

当前日期:

import datetime
Current_Date = datetime.datetime.today()
print (Current_Date)
Run Code Online (Sandbox Code Playgroud)

上次日期:

import datetime
Previous_Date = datetime.datetime.today() - datetime.timedelta(days=1) #n=1
print (Previous_Date)
Run Code Online (Sandbox Code Playgroud)

次日日期:

import datetime
NextDay_Date = datetime.datetime.today() + datetime.timedelta(days=1)
print (NextDay_Date)
Run Code Online (Sandbox Code Playgroud)


Sim*_*nde 5

如果你的论点是昨天、2天前、3个月前、2年前。下面的函数可能有助于获取参数的确切日期。您首先需要导入以下日期实用程序

import datetime
from dateutil.relativedelta import relativedelta
Run Code Online (Sandbox Code Playgroud)

然后实现下面的功能

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"
Run Code Online (Sandbox Code Playgroud)

然后您可以像这样调用该函数:

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')
Run Code Online (Sandbox Code Playgroud)