tags:

views:

65

answers:

2

Hi

How do I do a check in python that a date appears in the last year. i.e. date between now and (now-1 year)

Thanks

+2  A: 
In [10]: today=datetime.date.today()

In [11]: datetime.date(2010,5,5) < today
Out[11]: True

In [12]: today-datetime.timedelta(days=365) <= datetime.date(2010,5,5) < today
Out[12]: True

In [13]: today-datetime.timedelta(days=365) <= datetime.date(2009,5,5) < today
Out[13]: False

Edit: if today is the leap year 2000-2-29, then today-datetime.timedelta(days=365) is 1999-3-1. If you'd like one year ago to be 1999-2-28 then you could use

def add_years(date,num):
    try:
        result=datetime.date(date.year+num,date.month,date.day)
    except ValueError:
        result=datetime.date(date.year+num,date.month,date.day-1)
    return result

today=datetime.date(2000,2,29)
print(add_years(today,-1))
# 1999-02-28
unutbu
can i put datetime.timedelta(year=1) as some years will be 366 days with the leap year
John
@John: No you can't, read the documentation. The signature is *datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])* Does one day matter that much?
Felix Kling
yes if i want it one year from now.
John
+2  A: 

This should work for leap years:

>>> from datetime import date
>>> today = date.today()
>>> date(today.year - 1, today.month, today.day) < date(2009, 06, 05) <= today
True
>>> date(today.year - 1, today.month, today.day) < date(2009, 06, 04) <= today
False
>>> date(today.year - 1, today.month, today.day) < date(2010, 07, 04) <= today
False
fmark