我试图检查月份的第一个日期和月份的最后一个日期是否在一系列日期(范围是从当前日期开始的7天窗口)。下面是我试图实现的一个例子:
import datetime, calendar
today = datetime.date.today()
date_list = [today + datetime.timedelta(days=x) for x in range(0, 7)]
lastDayOfMonth = today.replace(day=calendar.monthrange(today.year,today.month)[-1])
if 1 in [ date_list[i].day for i in range(0, len(date_list))]:
print "we have first day of month in range"
elif lastDayOfMonth in [ date_list[i].day for i in range(0, len(date_list))]:
print " we have last date of month in the range"
我想知道是否有更清洁的方法吗?如果我在列表中找到它,我也想打印确切的日期,但我不知道如何在if语句中不扩展for循环,如果匹配我的条件则保存print date_list[i]
。因此,当我找到范围中的第一天时,我应该打印实际日期,而不是打印消息。最后一次约会。
提前致谢!
答案 0 :(得分:7)
我唯一可以提出的,无需使用迭代:
import datetime, calendar
today = datetime.date.today()
week_from_today = today + datetime.timedelta(days=6)
last_day_of_month = today.replace(day=calendar.monthrange(today.year,today.month)[-1])
if today.month != week_from_today.month:
print datetime.date(week_from_today.year, week_from_today.month, 1)
elif today <= last_day_of_month <= week_from_today:
print last_day_of_month
从今天起2016-06-02
测试代码很难
尝试将变量today
更改为另一天。我使用了日期2016-05-25
和2016-05-26
来测试代码。
设置自定义日期:today = datetime.date(yyyy, m, d)