Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Find a day dates between a range of two dates

I'm working on a project using python3 in which I have to consume an api and need to fetch the data for a specific Day of the week between a range a date.

So, the example input parameters are:

firstDay = '1-January-2000'
lastDay = '22-february-2000'
weekDay = 'Monday'

So, the date will be included in the API response but nothing has any information for the day. So, I have to get all the dates for a specific day like Monday between a date range.

According to the example above, how can I get the dates for all Mondays between firstDay and lastDay?

like image 375
Abdul Rehman Avatar asked Dec 13 '22 11:12

Abdul Rehman


1 Answers

from datetime import date, timedelta, datetime
import time

firstDay = '1-January-2000'
lastDay = '22-february-2000'
weekDay = 'Monday'

firstDay = datetime.strptime(firstDay, '%d-%B-%Y') 
lastDay = datetime.strptime(lastDay, '%d-%B-%Y')
dates = [firstDay + timedelta(days=x) for x in range((lastDay-firstDay).days + 1) if (firstDay + timedelta(days=x)).weekday() == time.strptime(weekDay, '%A').tm_wday]

output

dates
[datetime.datetime(2000, 1, 3, 0, 0),
 datetime.datetime(2000, 1, 10, 0, 0),
 datetime.datetime(2000, 1, 17, 0, 0),
 datetime.datetime(2000, 1, 24, 0, 0),
 datetime.datetime(2000, 1, 31, 0, 0),
 datetime.datetime(2000, 2, 7, 0, 0),
 datetime.datetime(2000, 2, 14, 0, 0),
 datetime.datetime(2000, 2, 21, 0, 0)]


The output in format weekDay-Month-year

[d.strftime("%A-%B-%Y") for d in dates] 

['Monday-January-2000',
 'Monday-January-2000',
 'Monday-January-2000',
 'Monday-January-2000',
 'Monday-January-2000',
 'Monday-February-2000',
 'Monday-February-2000',
 'Monday-February-2000']

output in firstDay format: 1-January-2000

[d.strftime("%-d-%B-%Y") for d in dates]   
['3-January-2000',
 '10-January-2000',
 '17-January-2000',
 '24-January-2000',
 '31-January-2000',
 '7-February-2000',
 '14-February-2000',
 '21-February-2000']
like image 171
frankegoesdown Avatar answered Jan 18 '23 16:01

frankegoesdown