John. B
John. B

Reputation: 53

Finding the dates of monday through sunday given the week day, and current date

I am currently working on a discord bot for one of my servers, and for this piece of it to work, I need it to bring up the dates for Monday through Sunday when given the current date, and week day. I would like to avoid using a lot of if statements if possible.

What I have tried: I have tried using if statements to complete this task, but just find it makes too much work, and messy code.

Parts of current code:

The Date

time = ctx.message.timestamp
day = time.day
month = time.month
year = time.year
date = [year, month, day]

The Week Day:

with open(dir_data + "Week Day.txt",'r+') as f:
    system_day = f.readline()

Note: The week day is in the form of a number. (Ex. Monday = 1)

Upvotes: 4

Views: 603

Answers (1)

lmiguelvargasf
lmiguelvargasf

Reputation: 69755

You can use the module weekday() to know the day of the week:

import datetime
datetime.datetime.today().weekday()

date.weekday() returns the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() is 2, which means it is a Wednesday.

In your case, you want to generate the days from Monday to Sunday, so the following function which returns a dictionary where its keys are the week days, and its values the dates corresponding to that day might be useful:

import datetime

def generate_week_days(date):
    weekday = date.weekday()
    offset = [i - weekday for i in range(7)]
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    dates = [(date + datetime.timedelta(days)).date() for days in offset] 

    return {days[date.weekday()]: date for date in dates}

Example:

d = datetime.datetime.now()
print(generate_week_days(d))

This will print:

{'Monday': datetime.date(2018, 7, 9),
 'Tuesday': datetime.date(2018, 7, 10),
 'Wednesday': datetime.date(2018, 7, 11),
 'Thursday': datetime.date(2018, 7, 12),
 'Friday': datetime.date(2018, 7, 13),
 'Saturday': datetime.date(2018, 7, 14),
 'Sunday': datetime.date(2018, 7, 15)}

Upvotes: 1

Related Questions