tkyass
tkyass

Reputation: 3186

python get day if its in a dates range

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!

Upvotes: 1

Views: 913

Answers (1)

user6410654
user6410654

Reputation:

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)

Upvotes: 4

Related Questions