在Python中检查仅包含月份和年份的日期范围

时间:2014-11-15 21:34:30

标签: python date

我只有monthyear,我想比较期间(整个月)是否在两个datetime个对象之间。例如,如果我有这两个日期:

min_post_date = 2013-03-07 00:00:00
max_post_date = 2014-01-01 00:00:00

我只有一年2013和一个月03,它应该给我True02-2013应该给False04-2014应该提供False,当然08-2013应该提供True

你会推荐什么?

感谢。

1 个答案:

答案 0 :(得分:2)

您可以先计算一个月的开头和结尾的两个日期:

from calendar import monthrange
from datetime import date, datetime

begin = date(year, month, 1)
end = date(year, month, monthrange(year, month)[1])

然后,您只需检查beginend是否在您的范围内:

(min_post_date <= begin <= max_post_date) or (min_post_date <= end <= max_post_date)

这是假设您使用以下内容解析min_post_datemax_post_date

min_post_date = datetime.strptime(min_post_date.split()[0], "%Y-%m-%d").date()

,同样适用于max_post_date