根据 Python 中的日期范围检查日期
问题描述
我有一个日期变量:2011-01-15
,如果所述日期在今天的 3 天内,我想返回一个布尔值.我不太确定如何在 Python 中构造它.我只处理日期,而不是日期时间.
I have a date variable: 2011-01-15
and I would like to get a boolean back if said date is within 3 days from TODAY. Im not quite sure how to construct this in Python. Im only dealing with date, not datetime.
我的工作示例是宽限期".用户登录我的网站,如果宽限期在今天的 3 天内,则该用户的其他脚本等将被省略.
My working example is a "grace period". A user logs into my site and if the grace period is within 3 days of today, additional scripts, etc. are omitted for that user.
我知道你可以在 Python 的日期模块中做一些花哨/复杂的事情,但我不知道去哪里找.
I know you can do some fancy/complex things in Python's date module(s) but Im not sure where to look.
解决方案
在 Python 中检查范围可以使用 a <= x <= b
:
In Python to check a range you can use a <= x <= b
:
>>> import datetime
>>> today = datetime.date.today()
>>> margin = datetime.timedelta(days = 3)
>>> today - margin <= datetime.date(2011, 1, 15) <= today + margin
True
相关文章