开发者

python date appears in last year

How do I do a check in python that a date appears in t开发者_高级运维he last year. i.e. date between now and (now-1 year)

Thanks


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜