1

I'm trying to check if first date of the month and the last date of the month lies in a range of dates (the range is 7 days window starting from current date) . below is an example for what I'm trying to achieve:

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"

I'm wondering if there is a cleaner way for doing that? I also want to print the exact date if I find it in the list but I don't know how without expanding the for loop in the if statement and save print date_list[i] if it matches my condition. so instead of printing the message when I find the first day in the range I should print the actual date. same for last date.

Thanks in advance!

tkyass
  • 2,968
  • 8
  • 38
  • 57
  • 2
    I don't know if I totally understand what you are trying to accomplish, but why not just grab the last day of the month and see if it's less than 6 days away? see: http://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python – Tyler Sebastian Jun 01 '16 at 19:36
  • `1 <= weekFromToday.day` this will only be True if "week from today" lies on the first day of the month. – Tadhg McDonald-Jensen Jun 01 '16 at 19:38
  • @TadhgMcDonald-Jensen you're right! I need to change that. Should I create a range then and check if day=1 lies in them? if so print it. – tkyass Jun 01 '16 at 19:53
  • I still don't understand what you are trying to do, are you trying to see if the week does not extend into the next month? Or are you trying to, given another date, see if it is within a week from the current date? If it is the second case use `today <= OTHER_DATE <= weekFromToday` and if the first case Tyler's suggestion would be the solution. – Tadhg McDonald-Jensen Jun 01 '16 at 19:58
  • I edited my question, I hope its clearer now! – tkyass Jun 01 '16 at 20:36

1 Answers1

4

The only thing I can come up with, without having to make use of iteration is:

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 

since today it's 2016-06-02 it's hard to test the code.
Try changing the variable today to another day. I used the dates 2016-05-25 and 2016-05-26 to test the code.

to set a custom date: today = datetime.date(yyyy, m, d)