1

I have a scenario where i want to fetch dates of last week of every month and store it to set

For example :

Let's assume this 2 parameter as Input : Todays month is JUL and current date date.today()

My code :

from datetime import date
from datetime import timedelta

def fetchLastWeekdate(month_name,current_date):
    today = date.today()

    for i in range(0,7):
        print (today - timedelta(days=i))

Printing Output :

2021-07-25
2021-07-24
2021-07-23
2021-07-22
2021-07-21
2021-07-20
2021-07-19

Expected Output :

But I need expected Output as following -> 25,26,27,28,29,30,31 as set

my_last_week_set  = {25,26,27,28,29,30,31}
1
  • 1
    Why are you passing current_date if you aren't going to use it? Actually, why do you have any parameters since you don't use them? Commented Jul 25, 2021 at 16:04

4 Answers 4

1

Pandas has some nice date features. Here I generate all last Sundays of the month in 2021 (if week start Monday as in Europe use weekday=0):

import pandas as pd

last_sunday_of_month = list(
    pd.date_range(start="1/1/2021", end="1/1/2022", freq="M")
    - pd.offsets.Week(weekday=6)
)

Then print all of the dates of the end of each month - here as lists. Conver to set will mess up the order:

for i in last_sunday_of_month:
    print(pd.date_range(i, i + pd.offsets.MonthEnd(1)).strftime("%d-%m").tolist())

Output:

['24-01', '25-01', '26-01', '27-01', '28-01', '29-01', '30-01', '31-01']
['21-02', '22-02', '23-02', '24-02', '25-02', '26-02', '27-02', '28-02']
['28-03', '29-03', '30-03', '31-03']
['25-04', '26-04', '27-04', '28-04', '29-04', '30-04']
['30-05', '31-05']
['27-06', '28-06', '29-06', '30-06']
['25-07', '26-07', '27-07', '28-07', '29-07', '30-07', '31-07']
['29-08', '30-08', '31-08']
['26-09', '27-09', '28-09', '29-09', '30-09']
['24-10', '25-10', '26-10', '27-10', '28-10', '29-10', '30-10', '31-10']
['28-11', '29-11', '30-11']
['26-12', '27-12', '28-12', '29-12', '30-12', '31-12']

The solution include the last whole week. Eg. last day of month is a sunday - then the whole last week is included.

1

I have also tried but the approach is little bit different , but it work like charm

My code :

Approach 1

import time
import calendar

my_list = time.strftime("%Y,%m")
tdetails=my_list.split(',')

#Get last date of month 
lastdateofmonth=calendar._monthlen(int(tdetails[0]), int(tdetails[1]))

lastweekdates = [ lastdateofmonth-int(x) for x in range(0,7) ]
print(lastweekdates)

Output :

Output

Approach 2

Incase want to try for any other month , take values from user like year , month

yr=int(input('Input your year : '))
mth=int(input('Input your month : '))
lastdateofmonth=calendar._monthlen(yr, mth)
lastweekdates = [ lastdateofmonth-int(x) for x in range(0,7) ]
print(lastweekdates)

Output :

Output

Approach 3 : using map

import time
import calendar

year , month = map(int,time.strftime("%Y %m").split())
lastdateofmonth=calendar._monthlen(year, month)
lastweekdates = [ lastdateofmonth-int(x) for x in range(0,7) ]
print(lastweekdates)

Output :

Output

If want to sort the last week dates of output just use : sorted()

print(sorted(lastweekdates))
0
import calendar as c
num_days = (c.monthrange(2021, 7)[1]) - 6
my_last_week_lst = [num_days + i for i in range(7)]
my_last_week_set = set(my_last_week_lst)
print(my_last_week_set)
0

As has been mentioned Pandas date_range would be useful here.

The following function will take the month name or number, and an optional year, and return the last 7 days of the specified month.

If you don't specify the year it defaults to the current year.

import pandas as pd

def fetchLastWeekdate(month_name, year=pd.to_datetime('today').year):
    first_day = f'{year}-{month_name}-1'
    last_day = pd.date_range(start=first_day, periods=1, freq='M').format()[0]
    days = [date.day for date in pd.date_range(start=first_day, end=last_day,freq='D').to_list()[-7:]]
    return days
>>> fetchLastWeekdate('FEB')
[22, 23, 24, 25, 26, 27, 28]
>>> fetchLastWeekdate('FEB', 2020)
[23, 24, 25, 26, 27, 28, 29]
>>> fetchLastWeekdate('DEC', 1983)
[25, 26, 27, 28, 29, 30, 31]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.