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
?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With