Copy the functions from below, then weeknumber(2020, 8, 21, 'Tuesday')
will give you the number of the week August 21, 2020 falls into, week count starting on Tuesday
, days in 2020 before the first Tuesday
will have week number 0
.
# necessary imports
from datetime import date, timedelta
import time
You can use this answer (which relies on this answer) to the question How can I select all of the Sundays for a year using Python? to get all Mondays, Tuesdays, Wednesdays, ... Sundays in a given year.
A helper function:
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
alternatively, (using this):
def weeknum(dayname):
return time.strptime('Sunday', "%A").tm_wday
The main function we are going to use:
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)
Now to get the number of week of a given date, do:
def weeknumber(year, month, day, weekstartsonthisday):
specificdays = [d for d in alldays(year, weekstartsonthisday)]
return len([specificday for specificday in specificdays if specificday <= datetime.date(year,month,day)])
specificdays
is a list of datetime.date
objects in the year being the same weekday as weekstartsonthisday
. For example, [d for d in alldays(2020,'Tuesday')]
starts like this:
[datetime.date(2020, 1, 7),
datetime.date(2020, 1, 14),
datetime.date(2020, 1, 21),
datetime.date(2020, 1, 28),
datetime.date(2020, 2, 4),
...
As a reminder, 2020 started like this:
The list [specificday for specificday in specificdays if specificday <= datetime.date(year,month,day)]
will contain the list of specificday
s (ie Mondays, Tuesdays, ..., whichever you specify) which happened in a given year before your date. The len() of this will give us the number of the week. Days in the year before the first specificday
will be in the 0
week.
Few examples:
weeknumber(2020,1,1,'Tuesday')
returns: 0
weeknumber(2020,1,6,'Tuesday')
returns: 0
weeknumber(2020,1,7,'Tuesday')
returns: 1
weeknumber(2020,12,31,'Tuesday')
returns: 52
weeknumber(2020,1,1,'Wednesday')
returns: 1
Seems good.
calendar
module allows to set thefirstweekday
but TBH I did not get how to go from adatetime
date to this sort of calendar... – Selfsacrificestrptime
and%j
if there is no direct way) and divide by 7? – Selfsacrifice