我有日期
date['min'] = '2013-11-11'
date['max'] = '2013-11-23'
如果日期在该范围内,是否有任何单行函数可以返回 true。
我的意思是如果只date.min
提供了,那么我需要检查给定的日期是否比它大,如果只提供最大值,那么我需要检查它是否小于那个。如果两者都提供,那么它是否属于它们之间
Dates in the form YYYY-MM-DD
can be compared alphabetically as well:
'2013-11-11' < '2013-11-15' < '2013-11-23'
date['min'] < your_date < date['max']
This won't work correctly for other formats, such as DD.MM.YYYY
or MM/DD/YYYY
. In that case you have to parse the strings and convert them into datetime
objects.
If don't know whether the min/max variables are present, you can do:
date.get('min', '0000-00-00') < your_date < date.get('max', '9999-99-99')
and replace the default text values with anything you prefer.
我认为简单的比较适用于此。
>>> from datetime import timedelta, date
>>> min_date = date.today()
>>> max_date = date.today() + timedelta(days=7)
>>> d1 = date.today() + timedelta(days=1)
>>> d2 = date.today() + timedelta(days=10)
>>> min_date < d1 < max_date
True
>>> min_date < d2 < max_date
False
这是更新的版本:
def is_in_range(d, min=date.min, max=date.max):
if max:
return min < d < max
return min < d
print is_in_range(d1, min_date, max_date)
print is_in_range(d2, min_date, max_date)
print is_in_range(d1, min_date)
print is_in_range(d2, min_date)
True
False
True
True
如果您处理日期对象:
from datetime import date
in_range = (first_date or date.min) < my_date < (second_date or date.max)