如何在Python中找到n天前的日期?

时间:2015-02-01 22:43:44

标签: python-2.7 date datetime timedelta

晚上很好,

我想编写一个脚本,我给python一些天(让我们称之为d),它给了我们d天前的日期。

我正在努力解决模块日期时间问题:

import datetime 

tod = datetime.datetime.now()
d = timedelta(days = 50) 
a = tod - h 
Type Error : unsupported operand type for - : "datetime.timedelta" and 
"datetime.datetime" 

感谢您的帮助

3 个答案:

答案 0 :(得分:10)

您已将某些内容与变量混合在一起,您可以从d中减去timedelta datetime.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

答案 1 :(得分:0)

如果您的论点类似于昨天,2天前,3个月前,2年前。下面的函数可能有助于获取参数的确切日期。 首先需要导入以下日期工具

import datetime
from dateutil.relativedelta import relativedelta

然后实现下面的功能

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"

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

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

答案 2 :(得分:0)

下面的代码应该可以工作

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