I want to generate a python list containing all months occurring between two dates, which is separated by year in array as follow:
startdate = "2014-10-10" # input start date
enddate = "2016-01-07" # input end date
month_list = [['Oct-14', 'Nov-14', 'Dec-14'], ['Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15', 'Jul-15', 'Aug-15', 'Sep-15', 'Oct-15', 'Nov-15', 'Dec-15'], ['Jan-16']] # output
i tried this but it display only two year interval in array
import calendar
from datetime import *
startdate = datetime.strptime("2015-09-10", "%Y-%m-%d")
enddate = datetime.strptime("2016-5-15", "%Y-%m-%d")
month_str = calendar.month_name
curryear = startdate.year
months = []
yearss=[]
temp=[]
while startdate < enddate:
month = startdate.month
year = startdate.year
day = startdate.day
mon_str = month_str[month][0:3]
next_month = month + 1 if month != 12 else 1
if curryear == year:
months.append("{0}-{1}".format(mon_str, str(year)[-2:]))
startdate = startdate.replace(month=next_month, year=year)
next_year = year+1 if next_month==1 else year
if curryear != next_year:
startdate = startdate.replace(month=next_month, year=next_year)
temp.append("{0}-{1}".format(mon_str, str(next_year)[-2:]))
months.append(temp)
print(months)
Output:
['Sep-15', 'Oct-15', 'Nov-15', 'Dec-15', ['Dec-16', 'Jan-16', 'Feb-16', 'Mar-16', 'Apr-16', 'May-16']]
Solution without pandas.
(you can also use it without dateutils)
(but then you've to manually count the months)
import datetime
from dateutil.relativedelta import relativedelta
startdate = datetime.datetime.strptime("2014-10-10", "%Y-%m-%d")
enddate = datetime.datetime.strptime("2016-01-07", "%Y-%m-%d")
# truncate the dates
startdate = startdate.replace(day=1)
enddate = enddate.replace(day=1)
# keep track of the series
dates = []
# create series by year
dates_years = []
current_year = startdate.year
while startdate <= enddate:
# if the current year is not equal to the value of startdate.year
if startdate.year != current_year:
# update current year
current_year = startdate.year
# add the dates_year to dates
dates.append(dates_years)
# empty dates_years
dates_years = []
# store the date in current year
dates_years.append(startdate.strftime("%b-%y"))
# add a month
startdate += relativedelta(months=1)
else:
# add the last part
if len(dates_years) > 0:
dates.append(dates_years)
result: dates
[['Oct-14', 'Nov-14', 'Dec-14'],
['Jan-15',
'Feb-15',
'Mar-15',
'Apr-15',
'May-15',
'Jun-15',
'Jul-15',
'Aug-15',
'Sep-15',
'Oct-15',
'Nov-15',
'Dec-15'],
['Jan-16']]
You can do this via pandas:
import numpy as np
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
startdate = "2014-10-10" # input start date
enddate = "2016-01-07"
## optionally - end date should be 1 + month, but date_range does also accept string-values
# cast the dates
startdate = datetime.date.fromisoformat(startdate)
enddate = datetime.date.fromisoformat(enddate) + relativedelta(months=1) # add 1 month
# convert to a data frame
dtr = pd.date_range(start=startdate, end=enddate, freq="M")
result
DatetimeIndex(['2014-10-31', '2014-11-30', '2014-12-31', '2015-01-31',
'2015-02-28', '2015-03-31', '2015-04-30', '2015-05-31',
'2015-06-30', '2015-07-31', '2015-08-31', '2015-09-30',
'2015-10-31', '2015-11-30', '2015-12-31', '2016-01-31'],
dtype='datetime64[ns]', freq='M')
step 2:
df = pd.DataFrame(dtr, columns=["dates"])
df['year'] = df.dates.dt.year
# add the result
df['output'] = [x.strftime("%b-%y") for x in df.dates]
result
dates year output
0 2014-10-31 2014 Oct-14
1 2014-11-30 2014 Nov-14
2 2014-12-31 2014 Dec-14
3 2015-01-31 2015 Jan-15
4 2015-02-28 2015 Feb-15
5 2015-03-31 2015 Mar-15
6 2015-04-30 2015 Apr-15
7 2015-05-31 2015 May-15
8 2015-06-30 2015 Jun-15
9 2015-07-31 2015 Jul-15
10 2015-08-31 2015 Aug-15
11 2015-09-30 2015 Sep-15
12 2015-10-31 2015 Oct-15
13 2015-11-30 2015 Nov-15
14 2015-12-31 2015 Dec-15
15 2016-01-31 2016 Jan-16
step 3
group by year, and add dates into a list:
[list(output) for year, output in df.groupby('year').output]
result
[['Oct-14', 'Nov-14', 'Dec-14'],
['Jan-15',
'Feb-15',
'Mar-15',
'Apr-15',
'May-15',
'Jun-15',
'Jul-15',
'Aug-15',
'Sep-15',
'Oct-15',
'Nov-15',
'Dec-15'],
['Jan-16']]
Related
Using Python...
How can I select all of the Sundays (or any day for that matter) in a year?
[ '01/03/2010','01/10/2010','01/17/2010','01/24/2010', ...]
These dates represent the Sundays for 2010. This could also apply to any day of the week I suppose.
You can use date from the datetime module to find the first Sunday in a year and then keep adding seven days, generating new Sundays:
from datetime import date, timedelta
def allsundays(year):
d = date(year, 1, 1) # January 1st
d += timedelta(days = 6 - d.weekday()) # First Sunday
while d.year == year:
yield d
d += timedelta(days = 7)
for d in allsundays(2010):
print(d)
Pandas has great functionality for this purpose with its date_range() function.
The result is a pandas DatetimeIndex, but can be converted to a list easily.
import pandas as pd
def allsundays(year):
return pd.date_range(start=str(year), end=str(year+1),
freq='W-SUN').strftime('%m/%d/%Y').tolist()
allsundays(2017)[:5] # First 5 Sundays of 2017
# ['01/01/2017', '01/08/2017', '01/15/2017', '01/22/2017', '01/29/2017']
Using the dateutil module, you could generate the list this way:
#!/usr/bin/env python
import dateutil.relativedelta as relativedelta
import dateutil.rrule as rrule
import datetime
year=2010
before=datetime.datetime(year,1,1)
after=datetime.datetime(year,12,31)
rr = rrule.rrule(rrule.WEEKLY,byweekday=relativedelta.SU,dtstart=before)
print rr.between(before,after,inc=True)
Although finding all Sundays is not too hard to do without dateutil, the module is handy especially if you have more complicated or varied date calculations.
If you are using Debian/Ubuntu, dateutil is provided by the python-dateutil package.
from datetime import date, timedelta
from typing import List
def find_sundays_between(start: date, end: date) -> List[date]:
total_days: int = (end - start).days + 1
sunday: int = 6
all_days = [start + timedelta(days=day) for day in range(total_days)]
return [day for day in all_days if day.weekday() is sunday]
date_start: date = date(2018, 1, 1)
date_end: date = date(2018, 12, 31)
sundays = find_sundays_between(date_start, date_end)
If looking for a more general approach (ie not only Sundays), we can build on sth's answer:
def weeknum(dayname):
if dayname == 'Monday': return 0
if dayname == 'Tuesday': return 1
if dayname == 'Wednesday':return 2
if dayname == 'Thursday': return 3
if dayname == 'Friday': return 4
if dayname == 'Saturday': return 5
if dayname == 'Sunday': return 6
This will translate the name of the day into an int.
Then do:
from datetime import date, timedelta
def alldays(year, whichDayYouWant):
d = date(year, 1, 1)
d += timedelta(days = (weeknum(whichDayYouWant) - d.weekday()) % 7)
while d.year == year:
yield d
d += timedelta(days = 7)
for d in alldays(2020,'Sunday'):
print(d)
Note the presence of % 7 in alldays(). This outputs:
2020-01-05
2020-01-12
2020-01-19
2020-01-26
2020-02-02
2020-02-09
2020-02-16
...
Can also do:
for d in alldays(2020,'Friday'):
print(d)
which will give you:
2020-01-03
2020-01-10
2020-01-17
2020-01-24
2020-01-31
2020-02-07
2020-02-14
...
You can iterate over a calendar for that year.
The below should return all Tuesdays and Thursdays for a given year.
# Returns all Tuesdays and Thursdays of a given year
from datetime import date
import calendar
year = 2016
c = calendar.TextCalendar(calendar.SUNDAY)
for m in range(1,13):
for i in c.itermonthdays(year,m):
if i != 0: #calendar constructs months with leading zeros (days belongng to the previous month)
day = date(year,m,i)
if day.weekday() == 1 or day.weekday() == 3: #if its Tuesday or Thursday
print "%s-%s-%s" % (year,m,i)
import time
from datetime import timedelta, datetime
first_date = '2021-01-01'
final_date = '2021-12-31'
first_date = datetime.strptime(first_date, '%Y-%m-%d')
last_date = datetime.strptime(final_date, '%Y-%m-%d')
week_day = 'Sunday'
dates = [first_date + timedelta(days=x) for x in range((last_date - first_date).days + 1) if (first_date + timedelta(days=x)).weekday() == time.strptime(week_day, '%A').tm_wday]
It will return all Sunday date of given date range.
Here's a complete generator function that builds on the solution from #sth. It includes the crucial fix that was mentioned in his solution's comments.
You can specify the day of week (using Python's indexing with 0=Monday to 6=Sunday), the starting date, and the number of weeks to enumerate.
def get_all_dates_of_day_of_week_in_year(day_of_week, start_year, start_month,
start_day, max_weeks=None):
'''
Generator function to enumerate all calendar dates for a specific day
of the week during one year. For example, all Wednesdays in 2018 are:
1/3/2018, 1/10/2018, 1/17/2018, 1/24/2018, 1/31/2018, 2/7/2018, etc.
Parameters:
----------
day_of_week : int
The day_of_week should be one of these values: 0=Monday, 1=Tuesday,
2=Wednesday, 3=Thursday, 4=Friday, 5=Saturday, 6=Sunday.
start_year : int
start_month : int
start_day : int
The starting date from which to list out all the dates
max_weeks : int or None
If None, then list out all dates for the rest of the year.
Otherwise, end the list after max_weeks number of weeks.
'''
if day_of_week < 0 or day_of_week > 6:
raise ValueError('day_of_week should be in [0, 6]')
date_iter = date(start_year, start_month, start_day)
# First desired day_of_week
date_iter += timedelta(days=(day_of_week - date_iter.weekday() + 7) % 7)
week = 1
while date_iter.year == start_year:
yield date_iter
date_iter += timedelta(days=7)
if max_weeks is not None:
week += 1
if week > max_weeks:
break
Example usage to get all Wednesdays starting on January 1, 2018, for 10 weeks.
import calendar
day_of_week = 2
max_weeks = 10
for d in get_all_dates_of_day_of_week_in_year (day_of_week, 2018, 1, 1, max_weeks):
print "%s, %d/%d/%d" % (calendar.day_name[d.weekday()], d.year, d.month, d.day)
The above code produces:
Wednesday, 2018/1/3
Wednesday, 2018/1/10
Wednesday, 2018/1/17
Wednesday, 2018/1/24
Wednesday, 2018/1/31
Wednesday, 2018/2/7
Wednesday, 2018/2/14
Wednesday, 2018/2/21
Wednesday, 2018/2/28
Wednesday, 2018/3/7
according to #sth answer I like to give you an alternative without a function
from datetime import date, timedelta,datetime
sunndays = list()
year_var = datetime.now() #get current date
year_var = year_var.year #get only the year
d = date(year_var, 1, 1) #get the 01.01 of the current year = 01.01.2020
#now we have to skip 4 days to get to sunday.
#d.weekday is wednesday so it has a value of 2
d += timedelta(days=6 - d.weekday()) # 01.01.2020 + 4 days (6-2=4)
sunndays.append(str(d.strftime('%d-%m-%Y'))) #you need to catch the first sunday
#here you get every other sundays
while d.year == year_var:
d += timedelta(days=7)
sunndays.append(str(d.strftime('%d-%m-%Y')))
print(sunndays) # only for control
if you want every monday for example
#for 2021 the 01.01 is a friday the value is 4
#we need to skip 3 days 7-4 = 3
d += timedelta(days=7 - d.weekday())
according to #sth answer,it will lost the day when 1st is sunday.This will be better:
d = datetime.date(year, month-1, 28)
for _ in range(5):
d = d + datetime.timedelta(days=-d.weekday(), weeks=1)
if d.month!=month:
break
date.append(d)
my df currently consists of only date column
date
28/09/1995
30/10/1993
26/02/2021
04/04/2020
I want to create 2 new columns called "end of month" which gives the last day of the month & "end of quarter" which gives last day of quarter
date end of month end of quarter
28/09/1995 30/09/1995 30/09/1995
30/10/1993 31/10/1993 31/12/1993
26/02/2021 28/02/2021 31/03/2021
04/04/2020 30/04/2020 30/06/2020
Kindly help me in solving this
Try this:
import pandas as pd
df = pd.DataFrame({'date':['28/09/1995', '30/10/1993', '26/02/2021', '04/04/2020']})
df['date'] = pd.to_datetime(df['date'], dayfirst=True)
df['end of month'] = df['date'] + pd.offsets.MonthEnd(1)
df['end of quarter'] = df['date'] + pd.offsets.QuarterEnd(1)
date end of month end of quarter
0 1995-09-28 1995-09-30 1995-09-30
1 1993-10-30 1993-10-31 1993-12-31
2 2021-02-26 2021-02-28 2021-03-31
3 2020-04-04 2020-04-30 2020-06-30
Using only the Python standard library:
from datetime import datetime, timedelta
def date_to_endofmonth(dt: datetime) -> datetime:
# reset day to first day of month, add one month and subtract 1 day:
return (datetime(dt.year + ((dt.month+1) // 12), ((dt.month+1) % 12) or 12, 1)
- timedelta(1))
def date_to_endofquarter(dt: datetime) -> datetime:
# from given month, calculate quarter end month, then hand over to date_to_endofmonth
return date_to_endofmonth(datetime(dt.year, ((dt.month - 1) // 3) * 3 + 3, dt.day))
Ex:
for s in "28/09/1995", "30/12/1993", "26/02/2021", "04/04/2020":
dt = datetime.strptime(s, "%d/%m/%Y")
print(s, '->', date_to_endofmonth(dt).date(), '->', date_to_endofquarter(dt).date())
28/09/1995 -> 1995-09-30 -> 1995-09-30
30/12/1993 -> 1993-12-31 -> 1993-12-31
26/02/2021 -> 2021-02-28 -> 2021-03-31
04/04/2020 -> 2020-04-30 -> 2020-06-30
I am trying to get a date of last 90 days Sundays (3 months Sunday) from the current date in python using datetime. I am able to get last 3 months Sunday but not from current date. With this code i am getting list of Sunday from the current month and last 2 month (total 3 months).
from datetime import date, timedelta, datetime
def list_sunday(year, month, day):
try:
for i in range(1,4):
d = date(year, month, day)
d += timedelta(days = 6 -d.weekday())
while d.month==month:
yield d
d += timedelta(days =+ 7)
if month > 1:
month = month - 1
else:
month = 12
year = year - 1
i+=1
except Exception as e:
log.error("XXX %s" % str(e))
for d in list_sunday(2019, 4, 05):
print d
With above code, i am getting this
2019-04-07
2019-04-14
2019-04-21
2019-04-28
2019-03-10
2019-03-17
2019-03-24
2019-03-31
2019-02-10
2019-02-17
2019-02-24
This is what i am trying to get,
2019-03-10
2019-03-17
2019-03-24
2019-03-31
2019-02-10
2019-02-17
2019-02-24
2019-01-06
2019-01-13
2019-01-20
2019-01-27
can someone help?
from datetime import date, timedelta
from pprint import pprint
def is_sunday(day):
return day.weekday() == 6
def sundays_within_last_x_days(num_days = 90):
result = []
end_date = date.today()
start_date = end_date - timedelta(days = num_days)
while start_date <= end_date:
if is_sunday(start_date):
result.append(start_date)
start_date += timedelta(days = 1)
return result
if __name__ == "__main__":
dates = sundays_within_last_x_days(30)
pprint(dates)
Resources
Python DateTime, TimeDelta, Strftime(Format) with Examples
datetime - Basic date and time types
pprint - Data pretty printer
This might give you a better approach based on your draft. For more information on how to understand more about this. Please follow the next link
from datetime import date, timedelta
def all_sundays(year):
# January 1st of the given year
dt = date(year, 1, 1)
# First Sunday of the given year
dt += timedelta(days = 6 - dt.weekday())
while dt.year == year:
yield dt
dt += timedelta(days = 7)
for s in all_sundays(2020):
print(s)
Output
2020-01-05
2020-01-12
2020-01-19
2020-01-26
2020-02-02
2020-12-06
2020-12-13
2020-12-20
2020-12-27
I have a pandas dataframe with three columns. A start and end date and a month.
I would like to add a column for how many days within the month are between the two dates. I started doing something with apply, the calendar library and some math, but it started to get really complex. I bet pandas has a simple solution, but am struggling to find it.
Input:
import pandas as pd
df1 = pd.DataFrame(data=[['2017-01-01', '2017-06-01', '2016-01-01'],
['2015-03-02', '2016-02-10', '2016-02-01'],
['2011-01-02', '2018-02-10', '2016-03-01']],
columns=['start date', 'end date date', 'Month'])
Desired Output:
start date end date date Month Days in Month
0 2017-01-01 2017-06-01 2016-01-01 0
1 2015-03-02 2016-02-10 2016-02-01 10
2 2011-01-02 2018-02-10 2016-03-01 31
There is a solution:
get a date list by pd.date_range between start and end dates, and then check how many date has the same year and month with the target month.
def overlap(x):
md = pd.to_datetime(x[2])
cand = [(ad.year, ad.month) for ad in pd.date_range(x[0], x[1])]
return len([x for x in cand if x ==(md.year, md.month)])
df1["Days in Month"]= df1.apply(overlap, axis=1)
You'll get:
start date end date date Month Days in Month
0 2017-01-01 2017-06-01 2016-01-01 0
1 2015-03-02 2016-02-10 2016-02-01 10
2 2011-01-02 2018-02-10 2016-03-01 31
You can convert your cell to datetime by
df = df.applymap(lambda x: pd.to_datetime(x))
Then find intersection days with function
def intersectionDaysInMonth(start, end, month):
end_month = month.replace(month=month.month + 1)
if month <= start <= end_month:
return end_month - start
if month <= end <= end_month:
return end - month
if start <= month < end_month <= end:
return end_month - month
return pd.to_timedelta(0)
Then apply
df['Days in Month'] = df.apply(lambda row: intersectionDaysInMonth(*row).days, axis=1)
Using Python...
How can I select all of the Sundays (or any day for that matter) in a year?
[ '01/03/2010','01/10/2010','01/17/2010','01/24/2010', ...]
These dates represent the Sundays for 2010. This could also apply to any day of the week I suppose.
You can use date from the datetime module to find the first Sunday in a year and then keep adding seven days, generating new Sundays:
from datetime import date, timedelta
def allsundays(year):
d = date(year, 1, 1) # January 1st
d += timedelta(days = 6 - d.weekday()) # First Sunday
while d.year == year:
yield d
d += timedelta(days = 7)
for d in allsundays(2010):
print(d)
Pandas has great functionality for this purpose with its date_range() function.
The result is a pandas DatetimeIndex, but can be converted to a list easily.
import pandas as pd
def allsundays(year):
return pd.date_range(start=str(year), end=str(year+1),
freq='W-SUN').strftime('%m/%d/%Y').tolist()
allsundays(2017)[:5] # First 5 Sundays of 2017
# ['01/01/2017', '01/08/2017', '01/15/2017', '01/22/2017', '01/29/2017']
Using the dateutil module, you could generate the list this way:
#!/usr/bin/env python
import dateutil.relativedelta as relativedelta
import dateutil.rrule as rrule
import datetime
year=2010
before=datetime.datetime(year,1,1)
after=datetime.datetime(year,12,31)
rr = rrule.rrule(rrule.WEEKLY,byweekday=relativedelta.SU,dtstart=before)
print rr.between(before,after,inc=True)
Although finding all Sundays is not too hard to do without dateutil, the module is handy especially if you have more complicated or varied date calculations.
If you are using Debian/Ubuntu, dateutil is provided by the python-dateutil package.
from datetime import date, timedelta
from typing import List
def find_sundays_between(start: date, end: date) -> List[date]:
total_days: int = (end - start).days + 1
sunday: int = 6
all_days = [start + timedelta(days=day) for day in range(total_days)]
return [day for day in all_days if day.weekday() is sunday]
date_start: date = date(2018, 1, 1)
date_end: date = date(2018, 12, 31)
sundays = find_sundays_between(date_start, date_end)
If looking for a more general approach (ie not only Sundays), we can build on sth's answer:
def weeknum(dayname):
if dayname == 'Monday': return 0
if dayname == 'Tuesday': return 1
if dayname == 'Wednesday':return 2
if dayname == 'Thursday': return 3
if dayname == 'Friday': return 4
if dayname == 'Saturday': return 5
if dayname == 'Sunday': return 6
This will translate the name of the day into an int.
Then do:
from datetime import date, timedelta
def alldays(year, whichDayYouWant):
d = date(year, 1, 1)
d += timedelta(days = (weeknum(whichDayYouWant) - d.weekday()) % 7)
while d.year == year:
yield d
d += timedelta(days = 7)
for d in alldays(2020,'Sunday'):
print(d)
Note the presence of % 7 in alldays(). This outputs:
2020-01-05
2020-01-12
2020-01-19
2020-01-26
2020-02-02
2020-02-09
2020-02-16
...
Can also do:
for d in alldays(2020,'Friday'):
print(d)
which will give you:
2020-01-03
2020-01-10
2020-01-17
2020-01-24
2020-01-31
2020-02-07
2020-02-14
...
You can iterate over a calendar for that year.
The below should return all Tuesdays and Thursdays for a given year.
# Returns all Tuesdays and Thursdays of a given year
from datetime import date
import calendar
year = 2016
c = calendar.TextCalendar(calendar.SUNDAY)
for m in range(1,13):
for i in c.itermonthdays(year,m):
if i != 0: #calendar constructs months with leading zeros (days belongng to the previous month)
day = date(year,m,i)
if day.weekday() == 1 or day.weekday() == 3: #if its Tuesday or Thursday
print "%s-%s-%s" % (year,m,i)
import time
from datetime import timedelta, datetime
first_date = '2021-01-01'
final_date = '2021-12-31'
first_date = datetime.strptime(first_date, '%Y-%m-%d')
last_date = datetime.strptime(final_date, '%Y-%m-%d')
week_day = 'Sunday'
dates = [first_date + timedelta(days=x) for x in range((last_date - first_date).days + 1) if (first_date + timedelta(days=x)).weekday() == time.strptime(week_day, '%A').tm_wday]
It will return all Sunday date of given date range.
Here's a complete generator function that builds on the solution from #sth. It includes the crucial fix that was mentioned in his solution's comments.
You can specify the day of week (using Python's indexing with 0=Monday to 6=Sunday), the starting date, and the number of weeks to enumerate.
def get_all_dates_of_day_of_week_in_year(day_of_week, start_year, start_month,
start_day, max_weeks=None):
'''
Generator function to enumerate all calendar dates for a specific day
of the week during one year. For example, all Wednesdays in 2018 are:
1/3/2018, 1/10/2018, 1/17/2018, 1/24/2018, 1/31/2018, 2/7/2018, etc.
Parameters:
----------
day_of_week : int
The day_of_week should be one of these values: 0=Monday, 1=Tuesday,
2=Wednesday, 3=Thursday, 4=Friday, 5=Saturday, 6=Sunday.
start_year : int
start_month : int
start_day : int
The starting date from which to list out all the dates
max_weeks : int or None
If None, then list out all dates for the rest of the year.
Otherwise, end the list after max_weeks number of weeks.
'''
if day_of_week < 0 or day_of_week > 6:
raise ValueError('day_of_week should be in [0, 6]')
date_iter = date(start_year, start_month, start_day)
# First desired day_of_week
date_iter += timedelta(days=(day_of_week - date_iter.weekday() + 7) % 7)
week = 1
while date_iter.year == start_year:
yield date_iter
date_iter += timedelta(days=7)
if max_weeks is not None:
week += 1
if week > max_weeks:
break
Example usage to get all Wednesdays starting on January 1, 2018, for 10 weeks.
import calendar
day_of_week = 2
max_weeks = 10
for d in get_all_dates_of_day_of_week_in_year (day_of_week, 2018, 1, 1, max_weeks):
print "%s, %d/%d/%d" % (calendar.day_name[d.weekday()], d.year, d.month, d.day)
The above code produces:
Wednesday, 2018/1/3
Wednesday, 2018/1/10
Wednesday, 2018/1/17
Wednesday, 2018/1/24
Wednesday, 2018/1/31
Wednesday, 2018/2/7
Wednesday, 2018/2/14
Wednesday, 2018/2/21
Wednesday, 2018/2/28
Wednesday, 2018/3/7
according to #sth answer I like to give you an alternative without a function
from datetime import date, timedelta,datetime
sunndays = list()
year_var = datetime.now() #get current date
year_var = year_var.year #get only the year
d = date(year_var, 1, 1) #get the 01.01 of the current year = 01.01.2020
#now we have to skip 4 days to get to sunday.
#d.weekday is wednesday so it has a value of 2
d += timedelta(days=6 - d.weekday()) # 01.01.2020 + 4 days (6-2=4)
sunndays.append(str(d.strftime('%d-%m-%Y'))) #you need to catch the first sunday
#here you get every other sundays
while d.year == year_var:
d += timedelta(days=7)
sunndays.append(str(d.strftime('%d-%m-%Y')))
print(sunndays) # only for control
if you want every monday for example
#for 2021 the 01.01 is a friday the value is 4
#we need to skip 3 days 7-4 = 3
d += timedelta(days=7 - d.weekday())
according to #sth answer,it will lost the day when 1st is sunday.This will be better:
d = datetime.date(year, month-1, 28)
for _ in range(5):
d = d + datetime.timedelta(days=-d.weekday(), weeks=1)
if d.month!=month:
break
date.append(d)